Flutter:如果对象的类型未知,则解码 Json

huangapple go评论69阅读模式
英文:

Flutter: Decoding Json if type of object is unknown

问题

我有三个实体类。例如,一个抽象的动物类,一个猫类和一个狗类,它们都扩展了动物类。狗类和猫类都有一个toJson()和fromJson()方法。
我正在从文件系统中读取一个文件。然后我在字符串上使用jsonDecode方法。
下一步将是调用jsonDecode()方法的结果的fromJson()方法。

但问题是:
它可能是一只狗或一只猫。所以我应该如何知道我应该调用哪个fromJson()方法?

String content = file.readAsStringSync();
Cat.fromJson(jsonDecode(content)); //它可能是一只狗

英文:

I've three entity classes. For example an abstract animal class, a cat and a dog class, which extend the animal class. The dog and cat class both have a toJson() and fromJson() method.
I'm reading a file from the file system. Then I'm using the jsonDecode method on the String.
Next step would be calling the fromJson() mehthod on the result of the jsonDecode() method.

But here is the problem:
It could be a dog or a cat. So how am I supposed to know, which fromJson() method I should call?

String content = file.readAsStringSync();
Cat.fromJson(jsonDecode(content)); //it could be a dog

答案1

得分: 1

有关字符串是否有什么不同之处吗?你是如何保存它们的?也许你应该在你的toJson方法中添加一个"type"或其他指示它是狗还是猫的内容,然后根据它来解析字符串。

英文:

Pascal! Is there something different about the strings ? How do you save'em ? Maybe you should add a "type" or something indicating if it's a Dog or a Cat to your toJson method and then parse the string by it.

huangapple
  • 本文由 发表于 2020年1月7日 00:14:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定