gpt4 book ai didi

json - 如何在 dart 中创建 json 可编码类

转载 作者:行者123 更新时间:2023-12-03 02:57:35 32 4
gpt4 key购买 nike

这个问题与this有关发布。

我尝试了以下代码:

import 'dart:convert';

/*server side Post class */
class Post {
int post_id;
String title;
String description;
DateTime posted_at;
DateTime last_edited;
String user;
String editor;
int up_votes;
int down_votes;
int total_votes;
String links_to;
List<String> tags = new List();

Post.fromSQL(List sql_post) {
//initialization code, unrelated.
}

Map toJson(){
Map fromObject = {
'post_id' : post_id,
'title' : title,
'description' : description,
'posted_at' : posted_at,
'last_edited' : last_edited,
'user' : user,
'editor' : editor,
'up_votes' : up_votes,
'dwon_votes' : down_votes,
'total_votes' : total_votes,
'links_to' : links_to,
'tags' : tags
};

return fromObject;
//I use the code below as a temporary solution
//JSON.encode(fromObject, toEncodable: (date)=>date.toString());
}
}

我有一个临时解决方案,但我真的希望能够执行以下操作。

JSON.encode(posts, toEncodable: (date)=>date.toString())

其中 posts 是 Post 对象的列表。我希望这能转换成 Post 类的 json 表示形式的 json 列表。我得到的是 "Instance of 'Post'" 字符串列表。所以问题是,这种语法是否不再受支持,还是我应该做些不同的事情?

最佳答案

看来你只能使用 toEncodable: OR toJson() 回退。

如果您将 Date 包装在提供 toJson() 的类中,则无需使用 toEncodable::

class JsonDateTime {
final DateTime value;
JsonDateTime(this.value);

String toJson() => value != null ? value.toIso8601String() : null;
}

class Post {
...
Map toJson() => {
'post_id' : post_id,
'title' : title,
'description' : description,
'posted_at' : new JsonDateTime(posted_at),
'last_edited' : new JsonDateTime(last_edited),
'user' : user,
'editor' : editor,
'up_votes' : up_votes,
'dwon_votes' : down_votes,
'total_votes' : total_votes,
'links_to' : links_to,
'tags' : tags
};
}

或者确保您的 toEncodeable: 处理每个不支持的类型:

print(JSON.encode(data, toEncodable: (value) {
if (value is DateTime) {
return value.toIso8601String();
} else {
return value.toJson();
}
}));

关于json - 如何在 dart 中创建 json 可编码类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30326838/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com