我想转换列表List<Word> myList
至String
并将其放入sharedPreference,稍后我还想将该字符串(从sharedPreference)转换回List<Word>
.
这是我的模型类 Word
class Word {
int id;
String word;
String meaning;
String fillInTheGapSentence;
Word.empty();
Word(int id, String word, String meaning, String fillInTheGapSentence){
this.id = id;
this.word = word;
this.meaning = meaning;
this.fillInTheGapSentence = fillInTheGapSentence;
}
}
我可以转换List<Word> myList
像这样的字符串
var myListString = myList.toString();
但无法制作List<Word> myListFromString
来自myListString
.
谢谢。
最佳答案
首先,myList.toString()
不是 JSON 格式,除非您重写 toString()
方法。您要做的就是手动将对象转换为字典,然后将其编码为 JSON 字符串。相反,您需要将字符串转换为字典,然后将其转换为对象。像这样的事情:
import 'dart:convert';
class Word {
int id;
String word;
String meaning;
String fillInTheGapSentence;
Word.empty();
Word(int id, String word, String meaning, String fillInTheGapSentence) {
this.id = id;
this.word = word;
this.meaning = meaning;
this.fillInTheGapSentence = fillInTheGapSentence;
}
Map<String, dynamic> toMap() {
return {
'id': this.id,
'word': this.word,
'meaning': this.meaning,
'fillInTheGapSentence': this.fillInTheGapSentence,
};
}
factory Word.fromMap(Map<String, dynamic> map) {
return new Word(
map['id'] as int,
map['word'] as String,
map['meaning'] as String,
map['fillInTheGapSentence'] as String,
);
}
}
String convertToJson(List<Word> words) {
List<Map<String, dynamic>> jsonData =
words.map((word) => word.toMap()).toList();
return jsonEncode(jsonData);
}
List<Word> fromJSon(String json) {
List<Map<String, dynamic>> jsonData = jsonDecode(json);
return jsonData.map((map) => Word.fromMap(map)).toList();
}
关于flutter - 将列表转换为 Json 字符串,然后将此字符串转换回 Dart 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143173/