gpt4 book ai didi

json - 如何解析嵌套的JSON字典( map )

转载 作者:行者123 更新时间:2023-12-03 04:39:35 29 4
gpt4 key购买 nike

我正在尝试将与Swift程序兼容的JSON代码读入Flutter应用程序。结构是这样的:

{
"tagDict" : {
"abc" : {
"helpHdr" : "short text1",
"helpText" : "long text1"
},
"def" : {
"helpHdr" : "short text2",
"helpText" : "long text2"
}
}
}
这将在Swift中创建一个字典,并在Dart中创建一个{key:{helpHdr,helpText}}类型的 map 。基于此的变量应启用label = myVariable [tag] .helpHdr,或与示例label = myVariable [“abc”]。helpHdr一起使用,应为标签分配“short text1”
为了解析嵌套数组,我正在使用它,但是,不知道如何将其传输到这样的嵌套映射。
class MyClass {
List<MySubClass> myArray;
MyClass({
this.myArray,
});

factory MyClass.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['myArray'] as List;
List<MySubClass> listObject = list.map((i) => MySubClass.fromJson(i)).toList();
return new MyClass(
myArray: listObject,
);
}
}

class MySubClass {
int id;
String text1;
String text2;
MySubClass({
this.id,
this.text1,
this.text2,
});

factory MySubClass.fromJson(Map<String, dynamic> parsedJson){
return new MySubClass(
id: parsedJson['id'],
text1: parsedJson['text1'],
text2: parsedJson['text2'],
);
}
}

最佳答案

如果我是正确的,您想将json解析为Data类对象。如果是这样,那么您可以尝试一下

void main() {
List<MyClass> myClassList = new List<MyClass>();
Map map = {
"tagDict": {
"abc": {"helpHdr": "short text1", "helpText": "long text1"},
"def": {"helpHdr": "short text2", "helpText": "long text2"}
}
};

map['tagDict'].forEach((key, value) {
value['id'] = key;
myClassList.add(MyClass.fromJson(value));
});

myClassList.forEach((myClass) {
print(myClass.id);
print(myClass.helpHdr);
print(myClass.helpText);
print("--------------------\n");
});
}

class MyClass {
String id;
String helpHdr;
String helpText;

MyClass({this.id, this.helpHdr, this.helpText});

MyClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
这是输出:
abc
short text1
long text1
--------------------

def
short text2
long text2
--------------------

关于json - 如何解析嵌套的JSON字典( map ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63490592/

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