英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论