Convert List to Json String then Convert this String back to List in Dart
First of all, myList.toString()
is not in JSON format, unless you override toString()
method. What you have to do is manually transform the object into a Dictionary then encoded it to JSON string. In reverse, you need to convert the string into a dictionary, then transform it into an object. Something like this:
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();
}
Al Walid Ashik
A mobile app developer who loves photography and having another passion inside the bottom of the heart is writing article about Entrepreneurship, Personal Growth, Life Lessons and obviously the fun part of programming.
Updated on December 15, 2022Comments
-
Al Walid Ashik over 1 year
I want to convert a list
List<Word> myList
toString
and put it into sharedPreference and later I also want to convert that string (from sharedPreference) back toList<Word>
.Here is my model class
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; } }
I can convert the
List<Word> myList
to String like thisvar myListString = myList.toString();
But couldn't make
List<Word> myListFromString
frommyListString
.Thanks.
-
sj_959 over 2 yearsThanks a lot! I got my code to work with a few tweaks in yours. (Specifically the
List<Map<String, dynamic>>
part infromJson
) -
Al Walid Ashik over 2 yearsawesome @sj_959