将列表转换为Json字符串,然后将此字符串转换回Dart中的List

时间:2019-12-02 16:39:40

标签: flutter dart converters typeconverter

我想将列表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转换为String

var myListString = myList.toString();

但是无法从List<Word> myListFromString中获得myListString

谢谢。

2 个答案:

答案 0 :(得分:0)

您将需要某种序列化,并且其中有很多。最受欢迎的一种是JSON序列化。

Flutter的文档很好,如何做到这一点: https://flutter.dev/docs/development/data-and-backend/json

您要:

  1. 将您的对象转换为Map
  2. 将您的地图编码为JSON(是字符串)
  3. 保存
  4. 将其检索为字符串
  5. 将您的JSON解码为Map
  6. 将地图转换为对象

答案 1 :(得分:0)

首先,myList.toString()并非JSON格式,除非您覆盖toString()方法。您要做的是手动将对象转换为Dictionary,然后将其编码为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();
}