【问题标题】:Flutter - The best way to parse a JSONFlutter - 解析 JSON 的最佳方式
【发布时间】:2021-04-07 14:53:38
【问题描述】:

我正在尝试将 JSON 解析为 Dart 中的对象,文档使用 Map 类型来解析 JSON 响应。我有大约 200 个数据表单 json 文件列表。

我的结果数据列出所有记录,并在颤动中将其呈现给 ListView。 我在 github 中有推送代码。 https://github.com/phuochoit/user_list

[
  id,
  name,
  username,
  email,
  phone 
] 

JSON

 {
      "type": "user",
      "format": "json",
      "version": "1.0",
      "data": {
        "Sincere@april.biz": {
          "id": 1,
          "name": "Leanne Graham",
          "username": "Bret",
          "email": "Sincere@april.biz",
          "address": {
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "city": "Gwenborough",
            "zipcode": "92998-3874",
            "geo": {
              "lat": "-37.3159",
              "lng": "81.1496"
            }
          },
          "phone": "1-770-736-8031 x56442",
          "website": "hildegard.org",
          "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
          }
        },
        "Shanna@melissa.tv": {
          "id": 2,
          "name": "Ervin Howell",
          "username": "Antonette",
          "email": "Shanna@melissa.tv",
          "address": {
            "street": "Victor Plains",
            "suite": "Suite 879",
            "city": "Wisokyburgh",
            "zipcode": "90566-7771",
            "geo": {
              "lat": "-43.9509",
              "lng": "-34.4618"
            }
          },
          "phone": "010-692-6593 x09125",
          "website": "anastasia.net",
          "company": {
            "name": "Deckow-Crist",
            "catchPhrase": "Proactive didactic contingency",
            "bs": "synergize scalable supply-chains"
          }
        },
.... to be continued
      }
    }

我有代码获取 json 文件并在 dart 中对其进行解码,但我没有将数据映射到渲染

Future<UserModel> fetchUser() async {
      final response = await http.get('http://172.16.0.2/data/users.json');
    
      if (response.statusCode == 200) {
        // If the server did return a 200 OK response,
        // then parse the JSON.
    
        return UserModel.fromJson(jsonDecode(response.body));
      } else {
        // If the server did not return a 200 OK response,
        // then throw an exception.
        throw Exception('Failed to load album');
      }
    }

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    将此与 quicktype 之类的东西进行比较: (1) 如果您没有模型类,请尝试使用 quicktype 之类的东西从示例 json 字符串中获取该类。 (2) 不过我建议不要使用quicktype给出的toJsonfromJson。原因是,当您的模型发生变化时(比如添加一个字段/更改一个字段),您必须也相应地更改您的 toJson/fromJson(这既费时又容易出错)。否则你会得到一个错误。

    如果您已经有了模型类并且只需要toJsonfromJson 方法:那么非常著名的json_serializable 包就适合您。它会愉快地生成toJsonfromJson

    比如说你有

    class Person {
      final String firstName;
      final String lastName;
      final DateTime dateOfBirth;
    }
    

    然后用一些样板代码,它会自动给你

    Person _$PersonFromJson(Map<String, dynamic> json) {
      return Person(
        firstName: json['firstName'] as String,
        lastName: json['lastName'] as String,
        dateOfBirth: DateTime.parse(json['dateOfBirth'] as String),
      );
    }
    
    Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
          'firstName': instance.firstName,
          'lastName': instance.lastName,
          'dateOfBirth': instance.dateOfBirth.toIso8601String(),
        };
    

    其实那个包比那个更强大。查看链接了解更多详情。

    【讨论】:

    • 谢谢。我会阅读 json_serializable 并再试一次。
    • @phuochq 不客气。如果此答案对您有帮助,您可以将其标记为“已接受”
    • 您好,我使用了它,但我遇到了问题。由于错误Instance of 'ListUser', Instance of 'ListUser',我无法使用数据。请克隆我的github。我在这里推送新代码link
    • @phuochq 请向您显示完整的堆栈跟踪和错误
    【解决方案2】:

    我建议使用 JSON 模型生成器,不要浪费时间重新发明轮子。

    我用https://app.quicktype.io/ 太棒了,输入 JSON,它会创建 Dart 类,小菜一碟,真的!

    例如这个 JSON:

        [{
      "_id": {
        "$oid": "5968dd23fc13ae04d9000001"
      },
      "product_name": "sildenafil citrate",
      "supplier": "Wisozk Inc",
      "quantity": 261,
      "unit_cost": "$10.47"
    }, {
      "_id": {
        "$oid": "5968dd23fc13ae04d9000002"
      },
      "product_name": "Mountain Juniperus ashei",
      "supplier": "Keebler-Hilpert",
      "quantity": 292,
      "unit_cost": "$8.74"
    }, {
      "_id": {
        "$oid": "5968dd23fc13ae04d9000003"
      },
      "product_name": "Dextromathorphan HBr",
      "supplier": "Schmitt-Weissnat",
      "quantity": 211,
      "unit_cost": "$20.53"
    }]
    

    它在 Dart 中生成了这个模型:

    // To parse this JSON data, do
    //
    //     final welcome = welcomeFromJson(jsonString);
    
    import 'dart:convert';
    
    List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));
    
    String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class Welcome {
        Welcome({
            this.id,
            this.productName,
            this.supplier,
            this.quantity,
            this.unitCost,
        });
    
        Id id;
        String productName;
        String supplier;
        int quantity;
        String unitCost;
    
        factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
            id: Id.fromJson(json["_id"]),
            productName: json["product_name"],
            supplier: json["supplier"],
            quantity: json["quantity"],
            unitCost: json["unit_cost"],
        );
    
        Map<String, dynamic> toJson() => {
            "_id": id.toJson(),
            "product_name": productName,
            "supplier": supplier,
            "quantity": quantity,
            "unit_cost": unitCost,
        };
    }
    
    class Id {
        Id({
            this.oid,
        });
    
        String oid;
    
        factory Id.fromJson(Map<String, dynamic> json) => Id(
            oid: json["\u0024oid"],
        );
    
        Map<String, dynamic> toJson() => {
            "\u0024oid": oid,
        };
    }
    

    【讨论】:

    • Map&lt;String, dynamic&gt; toJson() =&gt; { "Sincere@april.biz": sincereAprilBiz.toJson(), "Shanna@melissa.tv": shannaMelissaTv.toJson(), }; 谢谢。它给了我这个代码。我想如果我把所有的数据都放进去,它会非常大,客户的电子邮件也会被公开。这不好
    猜你喜欢
    • 2019-09-16
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多