【问题标题】:how to encode a json string in object list in flutter如何在颤动中对对象列表中的json字符串进行编码
【发布时间】:2020-05-23 16:11:10
【问题描述】:

我遇到了一个问题,我不明白出了什么问题,请帮忙。

我看到了这个遮阳篷,但我的问题没有解决。 Flutter Json Encode List

这里是json字符串:[{id: 4, quantity: 1, name: Implant, price: 7000}]

Services.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    quantity = json['quantity'];
    name = json['name'];
    price = json['price'];
  }

    print(_billModel.services);
    Iterable<dynamic> l = json.decode(_billModel.services.trim());

    var services = l.map((value) => Services.fromJson(value)).toList();

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    你需要添加这个关键字

        Services.fromJson(Map<String, dynamic> json) {
        this.id = json['id'];
        this.quantity = json['quantity'];
        this.name = json['name'];
        this.price = json['price'];
      }
        print(_billModel.services);
        Iterable<dynamic> l = json.decode(_billModel.services.trim());
    
        var services = l.map((value) => Services.fromJson(value)).toList();
    

    你想编码jsonstring然后使用下面的方法

     Map<String, dynamic> user = jsonDecode(jsonString);
    
    print('Howdy, ${user['name']}!');
    print('We sent the verification link to ${user['email']}.');
    

    对于内部模型类

    class User {
      final String name;
      final String email;
    
      User(this.name, this.email);
    
      User.fromJson(Map<String, dynamic> json)
          : name = json['name'],
            email = json['email'];
    
      Map<String, dynamic> toJson() =>
        {
          'name': name,
          'email': email,
        };
    }
    
    • User.fromJson() 构造函数,用于构造新的 User 实例 来自地图结构。
    • toJson() 方法,将 User 实例转换为地图。

    解码逻辑的职责现在移到了模型内部 本身。使用这种新方法,您可以轻松解码用户。

    Map userMap = jsonDecode(jsonString);
    var user = User.fromJson(userMap);
    
    print('Howdy, ${user.name}!');
    print('We sent the verification link to ${user.email}.');
    

    要对用户进行编码,请将 User 对象传递给 jsonEncode() 函数。 你不需要调用 toJson() 方法,因为 jsonEncode() 已经 为你做。

    String json = jsonEncode(user);
    

    欲了解更多信息,请阅读来自flutter.io的这篇文章

    【讨论】:

    • 希望你发现编辑过的有用。如果不告诉我
    【解决方案2】:
    child: new Card(
      child: new Container(
        child: Text("${data[index]["id"]} ${data[index]["quantity"]}",
       )),
    )
    

    这样试试,也许会成功

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 2011-06-24
      • 2011-10-06
      • 2012-12-23
      • 1970-01-01
      相关资源
      最近更新 更多