当前位置: 首页 > 知识库问答 >
问题:

如何在flutter dart上解析复杂的json

巫懿轩
2023-03-14

我从一个复杂的json中获取空数据,这里是json。当我试图解析它时,我得到了null。请看一看。

    {
        "billInfoList": [
            {
                "accountBalance": 0,
                "address": {
                    "street": "nd",
                    "complement": "df",
                    "city": "dsfs",
                    "neighborhood": "cxcnx",
                    "isForcedAddress": false,
                    "state": "ARE",
                    "zip": "00000",
                    "country": "hchchc",
                    "district": "ccc"
                },
                "billDay": 0,
                "billFrequency": 0,
                "billNumber": "hcc",
                "billType": 1cxc1,
                "creationDate": "2019-02-04",
                "dueDate": "2019-02-19",
                "servicePeriodEnd": "2019-02-04",
                "servicePeriodStart": "2019-01-29",
                "status": "Paid",
                "value": 0,
                "valueDisputed": 0,
                "valueOpen": 0
            },
            {
                "accountBalance": 0,
                "address": {
                    "street": "cxcvenciones ",
                    "complement": "Test124",
                    "city": "Arequipa",
                    "neighborhood": "Test4",
                    "isForcedAddress": false,
                    "state": "ARE",
                    "zip": "00320",
                    "country": "PE",
                    "district": "cquipa"
                },
                "billDay": 0,
                "billFrequency": 0,
                "billNumber": "dfs678",
                "billType": fds1,
                "billURL": "http://",
                "creationDate": "2019-01-29",
                "dueDate": "2019-02-13",
                "servicePeriodEnd": "2019-01-29",
                "servicePeriodStart": "2019-01-29",
                "status": "Paid",
                "value": 3.6,
                "valueDisputed": 0,
                "valueOpen": 0
            },
            {
                "accountBalance": 0,
                "address": {
                    "street": "fsdnciones ",
                    "complement": "Test124",
                    "city": "dfspa",
                    "neighborhood": "Test4",
                    "isForcedAddress": false,
                    "state": "ARE",
                    "zip": "3200",
                    "country": "PE",
                    "district": "requipa"
                },
                "billDay": 0,
                "billFrequency": 0,
                "billNumber": "323677",
                "billType": 341,
                "creationDate": "2019-01-29",
                "dueDate": "2019-02-13",
                "servicePeriodEnd": "2019-01-29",
                "servicePeriodStart": "2019-01-29",
                "status": "Pd",
                "value": 0,
                "valueDisputed": 0,
                "valueOpen": 0
            }
        ],
        "TransactionSequenceId": "hrhrhrh9",
        "ResponseCode": "hfhf00",
        "ResponseMessage": "Request Processed successfully"
    }

我已生成模型类:https://javiercbk.github.io/json_to_dart/

生成模型类后,创建一个新的类名ModelClass。

另一个类名为APiResponse并编写代码:这个类获取api响应并返回响应:APiResponse。fromJson(jsonDecode(response.body));

我尝试解析:

    APiResponse.fromJson(Map<String, dynamic> json)
          : results = new ModelClass.fromJson(json),          
            error = ""; 

模型类:

class ModelClass {
  List<BillInfoList> billInfoList;
  String transactionSequenceId;
  String responseCode;
  String responseMessage;

  ModelClass (
      {this.billInfoList,
      this.transactionSequenceId,
      this.responseCode,
      this.responseMessage});

  ModelClass.fromJson(Map<String, dynamic> json) {
    if (json['billInfoList'] != null) {
      billInfoList = new List<BillInfoList>();
      json['billInfoList'].forEach((v) {
        billInfoList.add(new BillInfoList.fromJson(v));
      });
    }
    transactionSequenceId = json['TransactionSequenceId'];
    responseCode = json['ResponseCode'];
    responseMessage = json['ResponseMessage'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.billInfoList != null) {
      data['billInfoList'] = this.billInfoList.map((v) => v.toJson()).toList();
    }
    data['TransactionSequenceId'] = this.transactionSequenceId;
    data['ResponseCode'] = this.responseCode;
    data['ResponseMessage'] = this.responseMessage;
    return data;
  }
}

class BillInfoList {
  int accountBalance;
  Address address;
  int billDay;
  int billFrequency;
  String billNumber;
  int billType;
  String creationDate;
  String dueDate;
  String servicePeriodEnd;
  String servicePeriodStart;
  String status;
  double value;
  int valueDisputed;
  int valueOpen;
  String billURL;

  BillInfoList(
      {this.accountBalance,
      this.address,
      this.billDay,
      this.billFrequency,
      this.billNumber,
      this.billType,
      this.creationDate,
      this.dueDate,
      this.servicePeriodEnd,
      this.servicePeriodStart,
      this.status,
      this.value,
      this.valueDisputed,
      this.valueOpen,
      this.billURL});

  BillInfoList.fromJson(Map<String, dynamic> json) {
    accountBalance = json['accountBalance'];
    address =
        json['address'] != null ? new Address.fromJson(json['address']) : null;
    billDay = json['billDay'];
    billFrequency = json['billFrequency'];
    billNumber = json['billNumber'];
    billType = json['billType'];
    creationDate = json['creationDate'];
    dueDate = json['dueDate'];
    servicePeriodEnd = json['servicePeriodEnd'];
    servicePeriodStart = json['servicePeriodStart'];
    status = json['status'];
    value = json['value'];
    valueDisputed = json['valueDisputed'];
    valueOpen = json['valueOpen'];
    billURL = json['billURL'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['accountBalance'] = this.accountBalance;
    if (this.address != null) {
      data['address'] = this.address.toJson();
    }
    data['billDay'] = this.billDay;
    data['billFrequency'] = this.billFrequency;
    data['billNumber'] = this.billNumber;
    data['billType'] = this.billType;
    data['creationDate'] = this.creationDate;
    data['dueDate'] = this.dueDate;
    data['servicePeriodEnd'] = this.servicePeriodEnd;
    data['servicePeriodStart'] = this.servicePeriodStart;
    data['status'] = this.status;
    data['value'] = this.value;
    data['valueDisputed'] = this.valueDisputed;
    data['valueOpen'] = this.valueOpen;
    data['billURL'] = this.billURL;
    return data;
  }
}

class Address {
  String street;
  String complement;
  String city;
  String neighborhood;
  bool isForcedAddress;
  String state;
  String zip;
  String country;
  String district;

  Address(
      {this.street,
      this.complement,
      this.city,
      this.neighborhood,
      this.isForcedAddress,
      this.state,
      this.zip,
      this.country,
      this.district});

  Address.fromJson(Map<String, dynamic> json) {
    street = json['street'];
    complement = json['complement'];
    city = json['city'];
    neighborhood = json['neighborhood'];
    isForcedAddress = json['isForcedAddress'];
    state = json['state'];
    zip = json['zip'];
    country = json['country'];
    district = json['district'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['street'] = this.street;
    data['complement'] = this.complement;
    data['city'] = this.city;
    data['neighborhood'] = this.neighborhood;
    data['isForcedAddress'] = this.isForcedAddress;
    data['state'] = this.state;
    data['zip'] = this.zip;
    data['country'] = this.country;
    data['district'] = this.district;
    return data;
  }
}

共有1个答案

百里嘉泽
2023-03-14

您可以使用此链接从json生成模型类https://app.quicktype.io/

import 'dart:convert';

BillInfoList billInfoListFromJson(String str) => BillInfoList.fromJson(json.decode(str));

String billInfoListToJson(BillInfoList data) => json.encode(data.toJson());

class BillInfoList {
    List<BillInfoListElement> billInfoList;
    String transactionSequenceId;
    String responseCode;
    String responseMessage;

    BillInfoList({
        this.billInfoList,
        this.transactionSequenceId,
        this.responseCode,
        this.responseMessage,
    });

    factory BillInfoList.fromJson(Map<String, dynamic> json) => BillInfoList(
        billInfoList: List<BillInfoListElement>.from(json["billInfoList"].map((x) => BillInfoListElement.fromJson(x))),
        transactionSequenceId: json["TransactionSequenceId"],
        responseCode: json["ResponseCode"],
        responseMessage: json["ResponseMessage"],
    );

    Map<String, dynamic> toJson() => {
        "billInfoList": List<dynamic>.from(billInfoList.map((x) => x.toJson())),
        "TransactionSequenceId": transactionSequenceId,
        "ResponseCode": responseCode,
        "ResponseMessage": responseMessage,
    };
}

class BillInfoListElement {
    int accountBalance;
    Address address;
    int billDay;
    int billFrequency;
    String billNumber;
    dynamic billType;
    DateTime creationDate;
    DateTime dueDate;
    DateTime servicePeriodEnd;
    DateTime servicePeriodStart;
    String status;
    double value;
    int valueDisputed;
    int valueOpen;
    String billUrl;

    BillInfoListElement({
        this.accountBalance,
        this.address,
        this.billDay,
        this.billFrequency,
        this.billNumber,
        this.billType,
        this.creationDate,
        this.dueDate,
        this.servicePeriodEnd,
        this.servicePeriodStart,
        this.status,
        this.value,
        this.valueDisputed,
        this.valueOpen,
        this.billUrl,
    });

    factory BillInfoListElement.fromJson(Map<String, dynamic> json) => BillInfoListElement(
        accountBalance: json["accountBalance"],
        address: Address.fromJson(json["address"]),
        billDay: json["billDay"],
        billFrequency: json["billFrequency"],
        billNumber: json["billNumber"],
        billType: json["billType"],
        creationDate: DateTime.parse(json["creationDate"]),
        dueDate: DateTime.parse(json["dueDate"]),
        servicePeriodEnd: DateTime.parse(json["servicePeriodEnd"]),
        servicePeriodStart: DateTime.parse(json["servicePeriodStart"]),
        status: json["status"],
        value: json["value"].toDouble(),
        valueDisputed: json["valueDisputed"],
        valueOpen: json["valueOpen"],
        billUrl: json["billURL"] == null ? null : json["billURL"],
    );

    Map<String, dynamic> toJson() => {
        "accountBalance": accountBalance,
        "address": address.toJson(),
        "billDay": billDay,
        "billFrequency": billFrequency,
        "billNumber": billNumber,
        "billType": billType,
        "creationDate": "${creationDate.year.toString().padLeft(4, '0')}-${creationDate.month.toString().padLeft(2, '0')}-${creationDate.day.toString().padLeft(2, '0')}",
        "dueDate": "${dueDate.year.toString().padLeft(4, '0')}-${dueDate.month.toString().padLeft(2, '0')}-${dueDate.day.toString().padLeft(2, '0')}",
        "servicePeriodEnd": "${servicePeriodEnd.year.toString().padLeft(4, '0')}-${servicePeriodEnd.month.toString().padLeft(2, '0')}-${servicePeriodEnd.day.toString().padLeft(2, '0')}",
        "servicePeriodStart": "${servicePeriodStart.year.toString().padLeft(4, '0')}-${servicePeriodStart.month.toString().padLeft(2, '0')}-${servicePeriodStart.day.toString().padLeft(2, '0')}",
        "status": status,
        "value": value,
        "valueDisputed": valueDisputed,
        "valueOpen": valueOpen,
        "billURL": billUrl == null ? null : billUrl,
    };
}

class Address {
    String street;
    String complement;
    String city;
    String neighborhood;
    bool isForcedAddress;
    String state;
    String zip;
    String country;
    String district;

    Address({
        this.street,
        this.complement,
        this.city,
        this.neighborhood,
        this.isForcedAddress,
        this.state,
        this.zip,
        this.country,
        this.district,
    });

    factory Address.fromJson(Map<String, dynamic> json) => Address(
        street: json["street"],
        complement: json["complement"],
        city: json["city"],
        neighborhood: json["neighborhood"],
        isForcedAddress: json["isForcedAddress"],
        state: json["state"],
        zip: json["zip"],
        country: json["country"],
        district: json["district"],
    );

    Map<String, dynamic> toJson() => {
        "street": street,
        "complement": complement,
        "city": city,
        "neighborhood": neighborhood,
        "isForcedAddress": isForcedAddress,
        "state": state,
        "zip": zip,
        "country": country,
        "district": district,
    };
}

我希望这能奏效

 类似资料:
  • 我收到了一个包含字符串和元组元素组合的CSV文件,但找不到正确解析它的方法。我错过了什么明显的东西吗? csvfile 第一行是标题,第二行开始数据 产量: csv.reader解析每行不同,因为结构复杂,嵌入了花括号元素。 ...但是我希望每行有20个元素。

  • 我有以下格式的json文件: 那么,我如何在pig中解析这个json。。 此外,categories和rep中可以有一些char。。可能并不总是空的。我做了以下尝试。 但我得到这个错误: 组织。科德豪斯。杰克逊。JsonParseException:意外字符('D'(代码68)):在[源代码:java.io]处应为有效值(数字、字符串、数组、对象、“true”、“false”或“null”)。By

  • 问题内容: 是否可以对JSON对象执行复杂的查询?我愿意接受JavaScript或jQuery解决方案,越轻松越好。我正在构想某种类似于LINQ或SQL的功能编程语言。 我不希望其他任何第三方库或附加组件。 更新 从早期答案的外观来看,将需要一个附加组件。在这种情况下,我更喜欢不需要安装过程的加载项。随软件发布一起部署的东西(如jQuery)很好(例如* .js文件集)。 问题答案: 签出:是否有

  • 在<code>go</code>中,标准包编码/json公开了<code>json。Unmarshal函数解析JSON。 可以在预定义中取消封送 JSON 字符串,也可以使用 并迭代意外 JSON 数据结构的结果。 也就是说,我无法正确解析复杂的 JSON。有人可以告诉我如何实现这一目标吗?

  • 问题内容: 我正在寻找一种将复杂文本文件解析为pandas DataFrame的简单方法。下面是一个示例文件,我希望解析后的结果是什么样,以及我当前的方法。 有什么方法可以使其更简洁/更快/更pythonic /更易读? 我也把这个问题放在了Code Review上 。 我最终写了一篇博客文章向初学者解释。 这是一个示例文件: 这是我希望解析后的结果看起来像什么: 这是我目前解析的方式: 问题答案