【问题标题】:how to parse a JSON in which some of the values do not have a key?如何解析其中一些值没有键的 JSON?
【发布时间】:2020-11-21 06:56:29
【问题描述】:

如果某些值没有键,我如何解析 json?

{
            "id": "123",
            "children": [
                "no_key_field_1",
                {
                    "id": "321",
                    "children": [
                        "no_key_field_2"
                    ]
                },
                "no_key_field_3"
            ]
        }

【问题讨论】:

  • 请在This Question查看答案
  • 你的意思是:“如何访问”?而不是“如何解析”(因为解析是通过json.decode方法完成的)?
  • @pskink 是的,我需要从中获取模型
  • 所以children 是一个数组,而不是映射,您可以通过arr[0]arr[1] 等获取它的项目

标签: flutter dart


【解决方案1】:

@pskink 是对的。你可以认为你的“孩子”是一个动态列表。您可以使用此模型将 JSON 转换为 Dart:


import 'dart:convert';

YourModel yourModelFromJson(String str) => YourModel.fromJson(json.decode(str));

String yourModelToJson(YourModel data) => json.encode(data.toJson());

class YourModel {
    YourModel({
        this.id,
        this.children,
    });

    String id;
    List<dynamic> children;

    factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
        id: json["id"] == null ? null : json["id"],
        children: json["children"] == null ? null : List<dynamic>.from(json["children"].map((x) => x)),
    );

    Map<String, dynamic> toJson() => {
        "id": id == null ? null : id,
        "children": children == null ? null : List<dynamic>.from(children.map((x) => x)),
    };
}

class ChildClass {
    ChildClass({
        this.id,
        this.children,
    });

    String id;
    List<String> children;

    factory ChildClass.fromJson(Map<String, dynamic> json) => ChildClass(
        id: json["id"] == null ? null : json["id"],
        children: json["children"] == null ? null : List<String>.from(json["children"].map((x) => x)),
    );

    Map<String, dynamic> toJson() => {
        "id": id == null ? null : id,
        "children": children == null ? null : List<dynamic>.from(children.map((x) => x)),
    };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 2013-03-27
    • 2015-09-13
    相关资源
    最近更新 更多