如何在扑扑中解析复杂的json

时间:2019-04-16 14:28:56

标签: arrays json list dart flutter

我很难从复杂的json获取数据,这是json

{
   "results":{
      "TotalRecordCount":"1",
      "Records":[
         {
            "code":"PCK_34333338365C93E2D50DB9C",
            "address":"1 AV KHEIREDDINE PACHA Imm Pacha centre BLOC B tunis Tunis 1000",
            "contact_phone":"99608258"
         }
      ],
      "Result":"OK"
   }
}

这是我制作的模型

import 'dart:convert';
class Pickup {
String status;
List message;
//Map<String ,dynamic> results;
Results results;
Pickup(
{this.status,
this.message,
this.results,
});
factory Pickup.fromJson(Map<String, dynamic> json) {
return Pickup(
status: json["status"] as String,
results: Results.fromJson(json["results"]),

);
}
}

class Results{
String TotalRecordCount;
records Records;

Results({this.TotalRecordCount,this.Records});

factory Results.fromJson(Map<String, dynamic> json) {
return Results(
TotalRecordCount: json["TotalRecordCount"],
Records:records.fromJson(json["Records"]),

);
}
}

class records{
String code;
String address;
String contact_phone;

records({this.code,this.address,this.contact_phone});
factory records.fromJson(Map<String, dynamic> json) {
return records(
code: json["code"],
address: json["address"],
contact_phone: json["contact_phone"],

);
}
}

现在我正在尝试解析记录以获取代码或地址并打印出来

if(response.statusCode == 200)
{
print(response.body);
final responseJson = json.decode(response.body);
var da=Pickup.fromJson(responseJson);
Results dat=da.results;
records data=dat.Records;
print(data.address);

response.body工作正常,但是当我尝试解析结果或记录时,我得到的“列表”不是“地图”类型错误的子类型

5 个答案:

答案 0 :(得分:1)

我们将解析一个复杂的JSON,其中包含一些字段和一组对象字段。看起来像这样:

{
  "title": "Dart Tutorial",
  "description": "Way to parse Json",
  "author": {
    "name": "bezkoder",
    "age": 30
  },
  "tags": [
    {
      "name": "dart",
      "quantity": 12
    },
    {
      "name": "flutter",
      "quantity": 25
    }
  ]
}

我们修改了Tutorial类,使其具有一个新的List<Tag>标签字段。

class Tutorial {
  String title;
  String description;
  User author;
  List<Tag> tags;

  Tutorial(this.title, this.description, this.author, [this.tags]);

  factory Tutorial.fromJson(dynamic json) {
    if (json['tags'] != null) {
      var tagObjsJson = json['tags'] as List;
      List<Tag> _tags = tagObjsJson.map((tagJson) => Tag.fromJson(tagJson)).toList();

      return Tutorial(
        json['title'] as String,
        json['description'] as String,
        User.fromJson(json['author']),
        _tags
      );
    } else {
      return Tutorial(
        json['title'] as String,
        json['description'] as String,
        User.fromJson(json['author'])
      );
    }
  }

  @override
  String toString() {
    return '{ ${this.title}, ${this.description}, ${this.author}, ${this.tags} }';
  }
}

–在构造方法中,我们使用方括号[this.tags]来指定此tags数组为选项字段。

–就像将JSON对象数组解析为Dart列表一样,我们使用map()toList()来获得List<Tag>

List<Tag> _tags = tagObjsJson.map((tagJson) => Tag.fromJson(tagJson)).toList();

main()函数现在看起来像这样。

import 'dart:convert';

main() {
  String complexText =
      '{"title": "Dart Tutorial", "description": "Way to parse Json", "author": {"name": "bezkoder", "age": 30}, "tags": [{"name": "dart", "quantity": 12}, {"name": "flutter", "quantity": 25}]}';

  Tutorial complexTutorial = Tutorial.fromJson(jsonDecode(complexText));

  print(complexTutorial);
}

运行上面的代码后,您可以看到带有标题,描述,作者,标签数组的结果。

{ Dart Tutorial, Way to parse Json, { bezkoder, 30 }, [{ dart, 12 }, { flutter, 25 }] }

基于:parse complex JSON

答案 1 :(得分:0)

答案 2 :(得分:0)

如何完成此操作的示例。

import 'dart:convert';

import 'json_objects.dart';

void main() {
  final responseJson = json.decode(responseBody) as Map<String, dynamic>;
  var da = Pickup.fromJson(responseJson);
  Results dat = da.results;
  List<ResultsRecords> data = dat.records;
  print(data[0].address);
}

var responseBody = '''
{
   "results":{
      "TotalRecordCount":"1",
      "Records":[
         {
            "code":"PCK_34333338365C93E2D50DB9C",
            "address":"1 AV KHEIREDDINE PACHA Imm Pacha centre BLOC B tunis Tunis 1000",
            "contact_phone":"99608258"
         }
      ],
      "Result":"OK"
   }
}''';

结果:

1 AV KHEIREDDINE PACHA Imm Pacha centre BLOC B tunis Tunis 1000

二手数据模型的源代码。

class Pickup {
  final Results results;

  Pickup({this.results});

  factory Pickup.fromJson(Map<String, dynamic> json) {
    return Pickup(
      results: _toObject(json['results'], (e) => Results.fromJson(e)),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'results': results?.toJson(),
    };
  }
}

class Results {
  final List<ResultsRecords> records;
  final String result;
  final String totalRecordCount;

  Results({this.records, this.result, this.totalRecordCount});

  factory Results.fromJson(Map<String, dynamic> json) {
    return Results(
      records:
          _toObjectList(json['Records'], (e) => ResultsRecords.fromJson(e)),
      result: json['Result'] as String,
      totalRecordCount: json['TotalRecordCount'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'Records': _fromList(records, (e) => e.toJson()),
      'Result': result,
      'TotalRecordCount': totalRecordCount,
    };
  }
}

class ResultsRecords {
  final String address;
  final String code;
  final String contactPhone;

  ResultsRecords({this.address, this.code, this.contactPhone});

  factory ResultsRecords.fromJson(Map<String, dynamic> json) {
    return ResultsRecords(
      address: json['address'] as String,
      code: json['code'] as String,
      contactPhone: json['contact_phone'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'address': address,
      'code': code,
      'contact_phone': contactPhone,
    };
  }
}

List _fromList(data, Function(dynamic) toJson) {
  if (data == null) {
    return null;
  }
  var result = [];
  for (var element in data) {
    var value;
    if (element != null) {
      value = toJson(element);
    }
    result.add(value);
  }
  return result;
}

T _toObject<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  return fromJson(data as Map<String, dynamic>);
}

List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  var result = <T>[];
  for (var element in data) {
    T value;
    if (element != null) {
      value = fromJson(element as Map<String, dynamic>);
    }
    result.add(value);
  }
  return result;
}

/*
Pickup:
  "results": Results

Results:
  "TotalRecordCount": String
  "Records": List<ResultsRecords>
  "Result": String

ResultsRecords:
  "code": String
  "address": String
  "contact_phone": String
*/

答案 3 :(得分:0)

我绝对会向您推荐这个网站json来使用飞镖App Quicktype,只是不要忘记选择右侧的Dart。

您只需将json放在la左边,就会给您这样的内容:

// To parse this JSON data, do
//
//     final pickUp = pickUpFromJson(jsonString);

import 'dart:convert';

PickUp pickUpFromJson(String str) => PickUp.fromJson(json.decode(str));

String pickUpToJson(PickUp data) => json.encode(data.toJson());

class PickUp {
    Results results;

    PickUp({
        this.results,
    });

    factory PickUp.fromJson(Map<String, dynamic> json) => new PickUp(
        results: Results.fromJson(json["results"]),
    );

    Map<String, dynamic> toJson() => {
        "results": results.toJson(),
    };
}

class Results {
    String totalRecordCount;
    List<Record> records;
    String result;

    Results({
        this.totalRecordCount,
        this.records,
        this.result,
    });

    factory Results.fromJson(Map<String, dynamic> json) => new Results(
        totalRecordCount: json["TotalRecordCount"],
        records: new List<Record>.from(json["Records"].map((x) => Record.fromJson(x))),
        result: json["Result"],
    );

    Map<String, dynamic> toJson() => {
        "TotalRecordCount": totalRecordCount,
        "Records": new List<dynamic>.from(records.map((x) => x.toJson())),
        "Result": result,
    };
}

class Record {
    String code;
    String address;
    String contactPhone;

    Record({
        this.code,
        this.address,
        this.contactPhone,
    });

    factory Record.fromJson(Map<String, dynamic> json) => new Record(
        code: json["code"],
        address: json["address"],
        contactPhone: json["contact_phone"],
    );

    Map<String, dynamic> toJson() => {
        "code": code,
        "address": address,
        "contact_phone": contactPhone,
    };
}

在开始时,它将告诉您如何使用它。

// To parse this JSON data, do
//
//     final pickUp = pickUpFromJson(jsonString);

因此,当您在代码中调用它时,它将变成这样。

  Future<Pickup> getPickup() async {
    var response = await http.get(url);
    return pickUpFromJson(response.body);
  }

例如,此代码可以调用FutureBuilder,也可以在将代码设置为等待将来的任何地方调用。

答案 4 :(得分:0)

{
   "results":{
      "TotalRecordCount":"1",
      "Records":[
         {
            "code":"PCK_34333338365C93E2D50DB9C",
            "address":"1 AV KHEIREDDINE PACHA Imm Pacha centre BLOC B tunis Tunis 1000",
            "contact_phone":"99608258"
         }
      ],
      "Result":"OK"
   }
}

上述 JSON 文件由其中的“记录”列表组成,因此使其成为复杂的 JSON。以下是我想对代码做出的修改 -

class Pickup {
  String status;
  List message;
  //Map<String ,dynamic> results;
  Results results;
  Pickup(
    {this.status,
     this.message,
     this.results,
  });
  factory Pickup.fromJson(Map<String, dynamic> json) {
    return Pickup(
             status: json["status"] as String,
             results: Results.fromJson(json["results"]),

           );
  }
}
class Results {
  String TotalRecordCount;
  records Records;

  Results({this.TotalRecordCount,this.Records});



    factory Results.fromJson(Map<String, dynamic> json) {
        //since records is a list hence it is parsed separately by creating a 
        //list out of it.  
    



       listOfRecords = (json["Records"] as List)
      .map((i) => records.fromJson(i))
      .toList();


 
    return Results(
    TotalRecordCount: json["TotalRecordCount"],
    Records:listOfRecords //now the list is used here directly
),

    );
  }
}

class records{
  String code;
  String address;
  String contact_phone;

  records({
    this.code,
    this.address,
    this.contact_phone
  });

  factory records.fromJson(Map<String, dynamic> json) {
    return records(
      code: json["code"],
      address: json["address"],
      contact_phone: json["contact_phone"],
    );
  }

最后,我们可以像这样在任何需要的地方使用它 -

if (response.statusCode == 200) {
  print(response.body);
  final responseJson = json.decode(response.body);
  var da = Pickup.fromJson(responseJson);
  Results dat = da.results;
  records data = dat.Records;
  print(data[0].address);  //since records was a list
}