gpt4 book ai didi

json - Flutter:JSON 循环

转载 作者:IT王子 更新时间:2023-10-29 06:36:06 29 4
gpt4 key购买 nike

我在Flutter中有一个Json解析项目,Json如下:

{
"Dependents":[
{
"Name": "Kim",
"Relationship": "Parent",
"Entitlements": [
{
"GP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"OPS": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"IP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"Dental": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"Optical": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"Maternity": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
}
]
},
{
"Name": "Tim",
"Relationship": "Spouse",
"Entitlements": [
{
"GP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"OPS": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"IP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"Maternity": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
}
]
},
{
"Name": "Lim",
"Relationship": "Child",
"Entitlements": [
{
"GP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"OPS": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"Dental": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"Optical": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"Maternity": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
}
]
},
{
"Name": "Xim",
"Relationship": "Child",
"Entitlements": [
{
"GP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"OPS": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
},
{
"IP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
}
]
}
]
}

如您所见,在Dependents 下有多个用户,在这些用户下他们有自己的Entitlements

我目前遇到的问题是:

我如何遍历 Entitlements 以打印出其下的所有 map ,因为每个用户都有不同的 Entitlements 与之关联。

请提供帮助。

最佳答案

您可以使用以下代码段:

  void iterateJson(String jsonStr) {
Map<String, dynamic> myMap = json.decode(jsonStr);
List<dynamic> entitlements = myMap["Dependents"][0]["Entitlements"];
entitlements.forEach((entitlement) {
(entitlement as Map<String, dynamic>).forEach((key, value) {
print(key);
(value as Map<String, dynamic>).forEach((key2, value2) {
print(key2);
print(value2);
});
});
});
}

尽管如果您不关心顺序,可以通过删除列表并只留下一张 map 来简化“权利”字段:

"Entitlements": {
"GP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
},
"OPS": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
},
"IP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
}

关于json - Flutter:JSON 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52034895/

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