Convert List to Json String then Convert this String back to List in Dart

3,461

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();
}

Share:
3,461
Al Walid Ashik
Author by

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, 2022

Comments

  • Al Walid Ashik
    Al Walid Ashik over 1 year

    I want to convert a list List<Word> myListto String and put it into sharedPreference and later I also want to convert that string (from sharedPreference) back to List<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 this

    var myListString = myList.toString();
    

    But couldn't make List<Word> myListFromString from myListString.

    Thanks.

  • sj_959
    sj_959 over 2 years
    Thanks a lot! I got my code to work with a few tweaks in yours. (Specifically the List<Map<String, dynamic>> part in fromJson)
  • Al Walid Ashik
    Al Walid Ashik over 2 years
    awesome @sj_959