Dart / Flutter Json 解析问题

Posted

技术标签:

【中文标题】Dart / Flutter Json 解析问题【英文标题】:Dart / Flutter Json Parsing Issue 【发布时间】:2021-07-10 09:35:00 【问题描述】:

我正在尝试解析我的 Json 响应看起来像的 Json


    "status": true,
    "orderList": 
        "current_page": 1,
        "data": [
            
                "orderId": 504,
                "orderNo": "ORD504",
                "restaurantId": 35,
                "restaurantName": "Burgerack",
                "address": "0A Edel Rd, Beyers Park, Boksburg, 1459, South Africa",
                "imageUlr": "uploads/restaurant/2011201907425023092019034122download (1).png",
                "createdAt": "20 Aug,2020 08:29 AM",
                "totalAmount": 155,
                "orderStatus": "Coming to You",
                "itemList": [
                    
                        "itemQty": "1",
                        "itemName": "Cheesy chilli fries"
                    ,
                    
                        "itemQty": "1",
                        "itemName": "Chicken Salad"
                    ,
                    
                        "itemQty": "1",
                        "itemName": "Kids Chicken Burger & fries(No garnish)"
                    
                ]
            ,
            
                "orderId": 503,
                "orderNo": "ORD503",
                "restaurantId": 45,
                "restaurantName": "McDonald's Rietfontien Road",
                "address": "Rietfontein Rd, Hughes, Boksburg, 1459, South Africa",
                "imageUlr": "uploads/restaurant/2011201907413931102019102725download.png",
                "createdAt": "20 Aug,2020 08:27 AM",
                "totalAmount": 139.9,
                "orderStatus": "Coming to You",
                "itemList": [
                    
                        "itemQty": "1",
                        "itemName": "Sausage McMuffin® with Egg Meal"
                    ,
                    
                        "itemQty": "1",
                        "itemName": "Breakfast Meal"
                    ,
                    
                        "itemQty": "1",
                        "itemName": "Medium Fries"
                    ,
                    
                        "itemQty": "1",
                        "itemName": "A la Carte"
                    
                ]
            
        ],
        "from": 1,
        "last_page": 1,
        "next_page_url": null,
        "path": "http://myurl.com/api/driver/order/my-accepted-orders",
        "per_page": 20,
        "prev_page_url": null,
        "to": 2,
        "total": 2
    

我正在使用下面的类来获取 json 并解析 我能够解析一个普通的 json 但不是我的

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:delivery_template/network_utils/api.dart';

class OrderList 
  final int currentPage;
  final List<Data> datas;

  OrderList(this.currentPage, this.datas);

  factory OrderList.fromJson(Map<String, dynamic> parsedJson) 
    var list = parsedJson['data'] as List;
    print(list.runtimeType);
    List<Data> datalist = list.map((i) => Data.fromJson(i)).toList();

    return OrderList(currentPage: parsedJson['current_page'], datas: datalist);
  


class Data 
  String orderId;
  String orderNo;

  Data.fromJson(Map<String, dynamic> jsonMap) 
    this.orderId = jsonMap['orderId'];
    this.orderNo = jsonMap['orderNo'];
  


class ActiveOrder 
  // final int orderId;
  // final String totalAmount;
  // final String restaurantName;
  // final String date;
  final List<OrderList> orders;

  //ActiveOrder(this.orderId, this.totalAmount, this.restaurantName, this.date);
  ActiveOrder(this.orders);

  factory ActiveOrder.fromJson(Map<String, dynamic> parsedJson) 
    var list = parsedJson['orderList'] as List;
    print(list.runtimeType);
    List<OrderList> orderList = list.map((i) => OrderList.fromJson(i)).toList();

    return ActiveOrder(orders: orderList);
  



class ActiveOrdersListView extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return FutureBuilder<List<ActiveOrder>>(
      future: _fetchOrders(),
      builder: (context, snapshot) 
        if (snapshot.hasData) 
          List<ActiveOrder> data = snapshot.data;
          return _ordersListView(data);
         else if (snapshot.hasError) 
          return Text("$snapshot.error");
        
        return CircularProgressIndicator();
      ,
    );
  

  Future<List<ActiveOrder>> _fetchOrders() async 
    var res = await Network().getData('/order/my-accepted-orders');
    if (res.statusCode == 200) 

      List jsonResponse = json.decode(res.body);
      return jsonResponse
          .map((i) => new ActiveOrder.fromJson(i))
          .toList();
     else 
      throw Exception('Failed to load jobs from API');
    
  

  ListView _ordersListView(data) 
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) 
          //   return _tile(
          //       data[index].restaurantName, data[index].orderId, Icons.work);
          // );
          return _tile("Test heading", "Test Subheading", Icons.work);
        );
  

  ListTile _tile(String title, String subtitle, IconData icon) => ListTile(
        title: Text(title,
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 20,
            )),
        subtitle: Text(subtitle),
        leading: Icon(
          icon,
          color: Colors.blue[500],
        ),
      );


我收到以下错误

类型 '_InternalLinkedHashMap' 不是类型 'List' 的子类型

我是 Flutter 的新手,非常初学者,谁能帮我解决这个问题

【问题讨论】:

您正在尝试像 List 一样对待地图,但它们是不同的。这就是错误的含义..如果您可以指定错误的确切位置(哪一行)..我将能够为您提供更多帮助 【参考方案1】:

您需要解析非常复杂的 JSON 数据。我建议您阅读这个article,它写得非常出色,并解释了 JSON 中的所有类型的解析。

【讨论】:

【参考方案2】:

json.decode(res.body) 返回的是 Map 而不是 List。

换行

列出 jsonResponse = json.decode(res.body);

var response = json.decode(res.body["]); List jsonResponse =response["orderList"]["data"];

【讨论】:

这实际上对我有用。但我仍然想以我们的模型方式工作。正如我在未来实施中需要它一样。你能引导我走过那条路吗? 我不明白你。能详细解释一下吗

以上是关于Dart / Flutter Json 解析问题的主要内容,如果未能解决你的问题,请参考以下文章

在 Flutter 和 Dart 中从 JSON 解析双精度值

Flutter - 网络请求与 json 解析

如果 Flutter/Dart 中没有名称/键,如何序列化/解析嵌套的 JSON 数组

如何在 Flutter 中只解析一次 JSON

解析json数组响应/颤动

将 Json 数据解析为现有的 Flutter 小部件