无法在flutter中将json解析为对象

问题描述 投票:0回答:3

寻求您的帮助。

实际上,我已经创建了一个对象模型类。但是,当我尝试解析对对象模型的 JSON 响应时,但出现如下错误:

JSON 响应

"value": [
    {
        "CardCode": "C20000",
        "CardName": "Maxi Teq",
        "DocCur": "AUD",
        "DocEntry": 793,
        "DocNum": 793,
        "DocTotal": 99.0,
        "DocType": "I",
        "U_Driver": "addon",
        "U_GLINK": "https://goo.gl/maps/tQJh7Zj9fpUzQqcv9"
    },
    {
        "CardCode": "C20000",
        "CardName": "Maxi Teq",
        "DocCur": "AUD",
        "DocEntry": 795,
        "DocNum": 795,
        "DocTotal": 99.0,
        "DocType": "I",
        "U_Driver": "addon",
        "U_GLINK": "https://goo.gl/maps/tQJh7Zj9fpUzQqcv9"
    }
]

型号 所有变量都是字符串,但 JSON 响应包括 int。

  import 'package:json_annotation/json_annotation.dart';
  
  part 'order.g.dart';
  
  @JsonSerializable(explicitToJson: true)
  class order {
    String? cardCode;
    String? cardName;
    String? docCur;
    String? docEntry;
    String? docNum;
    String? docTotal;
    String? docType;
    String? uDriver;
    String? uGLINK;
  
    order({this.cardCode, this.cardName, this.docCur, this.docEntry, this.docNum, this.docTotal, this.docType, this.uDriver, this.uGLINK});
  
    factory order.fromJson(Map<String,dynamic> data) => _$orderFromJson(data);
  
    Map<String,dynamic> toJson() => _$orderToJson(this);
  }

主班

  Map<String, dynamic> orderMap = json.decode(orderJson);
  List<dynamic> orderList = orderMap["value"];

  print("Method-------------$orderList");
  
  List<order> list = orderList.map((val) =>  order.fromJson(val)).toList();
  print(list.toString());

错误响应

I/flutter (26244): [Instance of 'order', Instance of 'order', Instance of 'order', Instance of 'order', Instance of 'order']

谢谢你

arrays json flutter
3个回答
0
投票

这不是一个错误。结果是:

print(list.toString());

您缺少的是类

toString()
上的
order
方法,因此它只是打印出您拥有
order
类型的实例列表。

将这样的内容添加到您的

order
课程中:

  @override
  String toString() {
    return 'order(cardCode: $cardCode, cardName: $cardName, docCur: $docCur, docEntry: $docEntry, docNum: $docNum, docTotal: $docTotal, docType: $docType, uDriver: $uDriver, uGLINK: $uGLINK)';
  }

0
投票

使用 orderList.elementAt(0) 获取值的映射。


0
投票

就像罗伯特·桑德伯格所说,这不是一个错误。只是因为您无法直接打印完整的嵌套对象。

因为你的问题似乎只是打印对象,我只是想添加一个额外的提示以使其更容易:

print(jsonEncode(order));

你应该先导入 jsonEncode

导入dart:转换;

然后运行它,您将在调试控制台中将完整的类打印为字符串

© www.soinside.com 2019 - 2024. All rights reserved.