gpt4 book ai didi

json - 动态键值json解析中的flutter问题

转载 作者:行者123 更新时间:2023-12-03 03:14:19 25 4
gpt4 key购买 nike

以下是我的 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"
}
]
}
}
这里的 key 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 为您制作的示例。

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});
}

让我知道它是否有效。

关于json - 动态键值json解析中的flutter问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63209286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com