假设我在Dart中有一个Diary
类,它是这样的
import 'dart:convert';
class Diary {
final DateTime createdDate;
final String? title;
final String body;
final String? mood;
// ...
Diary.fromJSON(Map<String, dynamic> diaryMap)
: createdDate = DateTime.parse(diaryMap['createdDate']),
body = diaryMap['body'],
title = diaryMap['title'],
mood = diaryMap['mood'];
}
到目前为止我写的代码是,
// jsonEntries is of type List<String> which are json encoded strings
final diaryEntries = jsonEntries.map((jsonEntry) => {
Diary.fromJSON(jsonDecode(jsonEntry))
}).toList();
print(diaryEntries.runtimeType);
// Expected List<Diary>
// But getting JSArray<Set<Diary>>
我应该在这里更改什么以获得预期的结果?我是新手,所以你的回答肯定对我有帮助。提前感谢!
我从你的句子中了解到,你有一个String
的List
命名为jsonEntries
,并且这个String列表的每一项都是json对象。如果jsonEntries
的每个项目都是一个json对象作为字符串,你应该获取Diary
项目的每个项目,像这样:
var diaryList = <Diary>[];/// diaryList is the list you want
for(var jsonItem in jsonEntries){
diaryList.add(Diary.fromJSON(jsonItem));
}
如果结果不是你想要的,请分享jsonEntries
来知道里面是什么。快乐编码…