【问题标题】:flutter problem in json parsing of dynamic key values动态键值的json解析中的颤振问题
【发布时间】:2020-11-22 07:56:06
【问题描述】:

以下是我的 JSON 的输出

{
    "success": true,
    "data": {
        "ones": [{
                "id": "2",
                "username": "LM10002"
            },
            {
                "id": "6",
                "username": "LM10006"
            }
        ],
        "twos": [{
                "id": "3",
                "username": "LM10003"
            },
            {
                "id": "8",
                "username": "LM10008"
            }
        ],
        "threes": [{
            "id": "4",
            "username": "LM10004"
        }],
        "fours": [{
                "id": "5",
                "username": "LM10005"
            },
            {
                "id": "14",
                "username": "GT10014"
            }
        ]
    }
}

这里的键 ones, twos, threes, fours 是动态键值 我尝试解析并能够获取的值

  DownLineModel({this.success, this.data});
  DownLineModel.fromJson(Map<String, dynamic> json) {
    success = json['success'];
    data = json['data'];
    print(data);

如何解析 json 并找到关键术语并再次解析它。

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    只需查看我根据您提供的 json 为您制作的示例即可。

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:json_parsing_example/models.dart';
    import 'package:http/http.dart' as http;
    
    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> {
      double value;
    
      String json = '''
      {
        "success": true,
        "data": {
            "ones": [{
                    "id": "2",
                    "username": "LM10002"
                },
                {
                    "id": "6",
                    "username": "LM10006"
                }
            ],
            "twos": [{
                    "id": "3",
                    "username": "LM10003"
                },
                {
                    "id": "8",
                    "username": "LM10008"
                }
            ],
            "threes": [{
                "id": "4",
                "username": "LM10004"
            }],
            "fours": [{
                    "id": "5",
                    "username": "LM10005"
                },
                {
                    "id": "14",
                    "username": "GT10014"
                }
            ]
        }
    }
      
      ''';
      @override
      void initState() {
        super.initState();
    
        getData();
      }
    
      getData() {
        Map mapValue = jsonDecode(json);
        // This is where you iterate via the data object
        // that is the value which is key,value pair
        List<Data> data = List();
        mapValue['data'].forEach((key, value) {
          List<User> user = List();
          value.forEach((item) {
            user.add(User(id: item['id'], username: item['username']));
          });
          data.add(Data(name: key, userList: user));
        });
    
        data.forEach((element) {
          print(element.name + " : " + '${element.userList.length}');
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(child: Text('s')),
        );
      }
    }
    
    class Data {
      final String name;
      final List<User> userList;
    
      Data({this.name, this.userList});
    }
    
    class User {
      final String id;
      final String username;
    
      User({this.id, this.username});
    }
    
    

    让我知道它是否有效。

    【讨论】:

      【解决方案2】:

      除非this.dataMap&lt;dynamic, dynamic&gt;,否则您的代码将无法工作。您必须使用自己的 DataModel.fromJson(Map json) 方法为 data 属性创建一个单独的类。然后在 DownLineModel 构造函数中,您可以像这样简单地解析数据 json:

      this.data = DataModel.fromJson(jsonData);
      

      【讨论】:

        【解决方案3】:

        json['data'] 将是 Map&lt;String, dynamic&gt;。因此,您可以使用 forEach 迭代这些动态键。

        json['data'].forEach((dynamicKey, list) {
          // dynamicKey will be 'ones', 'twos', ....
          // list will be the corresponding list of maps
        });
        

        【讨论】:

          【解决方案4】:

          假设当你这样做print(data),你得到这个响应

              {
                  "ones": [{
                          "id": "2",
                          "username": "LM10002"
                      },
                      {
                          "id": "6",
                          "username": "LM10006"
                      }
                  ],
                  "twos": [{
                          "id": "3",
                          "username": "LM10003"
                      },
                      {
                          "id": "8",
                          "username": "LM10008"
                      }
                  ],
                  "threes": [{
                      "id": "4",
                      "username": "LM10004"
                  }],
                  "fours": [{
                          "id": "5",
                          "username": "LM10005"
                      },
                      {
                          "id": "14",
                          "username": "GT10014"
                      }
                  ]
              }
          

          现在,我们可以做的是,再次遍历数据,并找到dynamic keys,如onestwos....

          我们可以做这样的事情。我只为ones 向您展示,您可以为资源做这些

          //for ones
          List<Map<String, String>> ones = data["ones"];
          
          //iterating over it
          ones.forEach((element){
             // we are now inside the array
             // iterating over element which is {"id": "", "username": ""}
             element.forEach((key, value){
                print("$key => $value");
             });
          });
          
          // OUTPUT
          // id => 2
          // username => LM10002
          // id => 6
          // username => LM10006
          

          【讨论】:

            猜你喜欢
            • 2021-11-04
            • 2019-01-17
            • 2021-10-27
            • 2023-03-05
            • 2020-10-14
            • 2021-11-14
            • 2021-08-23
            • 2020-03-01
            • 2021-09-25
            相关资源
            最近更新 更多