【问题标题】:Convert List to Json String then Convert this String back to List in Dart将列表转换为 Json 字符串,然后将此字符串转换回 Dart 中的列表
【发布时间】:2019-12-02 16:39:40
【问题描述】:

我想将列表 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();

但无法从myListString 生成List<Word> myListFromString

谢谢。

【问题讨论】:

    标签: flutter dart converters typeconverter


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!我让我的代码与你的一些调整一起工作。 (特别是fromJson 中的List&lt;Map&lt;String, dynamic&gt;&gt; 部分)
    • 真棒@sj_959
    【解决方案2】:

    您将需要某种序列化,其中有很多。最流行的一种是 JSON 序列化。

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

    你想:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 2021-01-06
      • 1970-01-01
      • 2014-05-23
      相关资源
      最近更新 更多