【问题标题】:Cannot iterate through the JSON object because of the unwanted keys由于不需要的键,无法遍历 JSON 对象
【发布时间】:2020-07-10 15:00:06
【问题描述】:

我的 JSON 响应对象是这样的

{
    "response": "success",
    "message": "done",
    "data": {
        "orders": {
            "order4": {
                "OrderId": "4",
                "OrderSubTotal": "568",
                "Items": {
                    "1": {
                        "ProductName": "Prod 1",
                        "ItemDiscount": "10",
                        "Quantity": "3",
                        "TotalItemPrice": "161.865"
                    },
                    "2": {
                        "ProductName": "Prod 2",
                        "ItemDiscount": "0",
                        "Quantity": "5",
                        "TotalItemPrice": "449.75"
                    }
                },
                "order6": {
                    "OrderId": "6",
                    "total": "789",
                    "Items": {
                        "1": {
                            "ProductName": "Prod 1",
                            "ItemDiscount": "10",
                            "Quantity": "3",
                            "TotalItemPrice": "161.865"
                        },
                        "2": {
                            "ProductName": "Prod 2",
                            "ItemDiscount": "0",
                            "Quantity": "5",
                            "TotalItemPrice": "449.75"
                        }
                    }
                }

            }
        }
    }
}

问题是我无法遍历这些字段,因为我得到了像 order6、order4 这样的随机键。那么有没有办法从对象中删除这些键并创建一个干净的 JSON 对象。我用飞镖语言编码。

【问题讨论】:

  • 您使用的是哪种语言?
  • 带有 dart 的颤振框架。我在描述中添加了这一点。
  • 你的 json 是一个字符串?
  • 你这是什么意思?
  • 我的意思是如果json只是一个字符串,所以我们需要先序列化它。

标签: json flutter dart httprequest


【解决方案1】:

如果我知道你想要什么,那么SplayTreeMap.from(map, comparator) 可以为你完成这项工作,如下代码所示:

import 'dart:convert';
import 'dart:collection';

void main() {
  String str = r'''{
    "response": "success",
    "message": "done",
    "data": {
        "orders": {
            "order6": {
                "OrderId": "6",
                "total": "789",
                "Items": {
                    "1": {
                        "ProductName": "Prod 1",
                        "ItemDiscount": "10",
                        "Quantity": "3",
                        "TotalItemPrice": "161.865"
                    },
                    "2": {
                        "ProductName": "Prod 2",
                        "ItemDiscount": "0",
                        "Quantity": "5",
                        "TotalItemPrice": "449.75"
                    }
                }
            },
            "order4": {
                "OrderId": "4",
                "OrderSubTotal": "568",
                "Items": {
                    "1": {
                        "ProductName": "Prod 1",
                        "ItemDiscount": "10",
                        "Quantity": "3",
                        "TotalItemPrice": "161.865"
                    },
                    "2": {
                        "ProductName": "Prod 2",
                        "ItemDiscount": "0",
                        "Quantity": "5",
                        "TotalItemPrice": "449.75"
                    }
                }
            }
        }
    }
}''';
  
  final sortedMap = new SplayTreeMap<String,dynamic>.from(jsonDecode(str)["data"]["orders"], (a,b)=>a.compareTo(b));
  print(sortedMap);
} 

【讨论】:

    【解决方案2】:

    看看我根据你提供的 json 制作的这个例子:

    以下是您提供的示例 json:

    {
        "response": "success",
        "message": "done",
        "data": {
            "orders": {
                "order6": {
                    "OrderId": "6",
                    "total": "789",
                    "Items": {
                        "1": {
                            "ProductName": "Prod 1",
                            "ItemDiscount": "10",
                            "Quantity": "3",
                            "TotalItemPrice": "161.865"
                        },
                        "2": {
                            "ProductName": "Prod 2",
                            "ItemDiscount": "0",
                            "Quantity": "5",
                            "TotalItemPrice": "449.75"
                        }
                    }
                },
                "order4": {
                    "OrderId": "4",
                    "OrderSubTotal": "568",
                    "Items": {
                        "1": {
                            "ProductName": "Prod 1",
                            "ItemDiscount": "10",
                            "Quantity": "3",
                            "TotalItemPrice": "161.865"
                        },
                        "2": {
                            "ProductName": "Prod 2",
                            "ItemDiscount": "0",
                            "Quantity": "5",
                            "TotalItemPrice": "449.75"
                        }
                    }
                }
            }
        }
    }
    

    基于 json 我为您制作了一个 ui 来显示订单详情:

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(home: HomePage());
      }
    }
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      List<Order> ordersList = List();
      @override
      void initState() {
        super.initState();
        getData();
      }
    
      getData() async {
        String data =
            await DefaultAssetBundle.of(context).loadString("json/parse.json");
    
        Map newMap = json.decode(data);
    
        newMap['data'].forEach((k, v) {
          
          v.forEach((key, val) {
            String ordername = key;
            List<Item> items = List();
           
            
            val['Items'].forEach((key, value) {
              print('sample');
              Item item = Item(
                productNumber: key,
                productName: value['ProductName'],
                itemDiscount: value['ItemDiscount'],
                quantity: value['Quantity'],
                totalItemPrice: value['TotalItemPrice'],
              );
              items.add(item);
    
              print(key);
              print(value);
              print('length is :${items.length}');
            });
    
            Order order = Order(
                orderId: val['OrderId'],
                orderName: ordername,
                total: val['total'],
                items: items);
    
            ordersList.add(order);
          });
        });
        setState(() {});
    
        print('This is the list : count ${ordersList.length}');
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Container(
          child: ListView.builder(
              itemCount: ordersList.length,
              shrinkWrap: true,
              itemBuilder: (context, index) {
                var order = ordersList[index];
                return Card(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text('Order Name : ${order.orderName}'),
                      Text('Order Id : ${order.orderId}'),
                      Text('Order total : ${order.total}'),
                      Text('Order Items: ${order.items.length}')
                    ],
                  ),
                );
              }),
        ));
      }
    }
    
    class Order {
      final String orderName;
      final String orderId;
      final String total;
      final List<Item> items;
    
      Order({this.orderName, this.orderId, this.total, this.items});
    }
    
    class Item {
      Item({
        this.productName,
        this.itemDiscount,
        this.quantity,
        this.totalItemPrice,
        this.productNumber,
      });
      String productNumber;
      String productName;
      String itemDiscount;
      String quantity;
      String totalItemPrice;
    }
    
    
    

    也许我很困惑的是您提供的 json 是否正确,请检查它在 order 4 中是否有 order6,并且 OrderSubTotal 和 total 有关心的参数,如果事情正确,请告诉我。

    检查一下,让我知道它是否有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      相关资源
      最近更新 更多