将JSON映射到类对象

编程入门 行业动态 更新时间:2024-10-12 01:25:35
本文介绍了将JSON映射到类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图将JSON文件映射到类对象中,然后根据新接收的JSON更新卡。

I am trying to map my JSON file into a class object, and then update the cards based on the newly received JSON.

我的JSON结构如下

{ "$class": "FirstCard", "id": "1", "description": "I am card number one", "Role": "attack", "score": 0, "tag": [ "string" ],................}

我的班级是这样的:

class CardInfo { //Constructor String id; String description; String role; int score; }

如何将JSON文件中的值映射到从CardInfo类创建的对象的字段?

How can I map the values in my JSON file into the fields of objects created from CardInfo class?

更新

以下试验打印在 ci.description 中为null,是否表示从未创建对象?

the following trial prints null at ci.description, does this mean the object was never created ?

const jsonCodec = const JsonCodec _loadData() async { var url = 'myJsonURL'; var httpClient = createHttpClient(); var response =await httpClient.get(url); print ("response" + response.body); Map cardInfo = jsonCodec.decode(response.body); var ci = new CardInfo.fromJson(cardInfo); print (ci.description); //prints null }

Update2

打印cardInfo提供以下内容:

Printing cardInfo gives the following:

{$ class:FirstCard,id:1,description :我是卡号第一,........}

{$class: FirstCard, id: 1, description: I am card number one,........}

请注意,它类似于原始JSON,但没有双精度字符串值的引号。

Note that it resembles the original JSON but without the double quotes on string values.

推荐答案

class CardInfo { //Constructor String id; String description; String role; int score; CardInfo.fromJson(Map json) { this.id = json['id']; this.description = json['description']; this.role = json['Role']; this.score = json['score']; } } var ci = new CardInfo.fromJson(myJson);

您可以使用源生成工具,例如 github/dart-lang/source_gen pub.dartlang/packages/json_serializable 为您生成序列化和反序列化代码。

You can use source generation tools like github/dart-lang/source_gen pub.dartlang/packages/json_serializable to generate the serialization and deserialization code for you.

如果您喜欢使用不可变的类,请 pub.dartlang/packages/built_value 是个好选择。

If you prefer using immutable classes pub.dartlang/packages/built_value is a good bet.

更多推荐

将JSON映射到类对象

本文发布于:2023-11-26 08:46:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!