我在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下有多个用户,而在这些用户下,他们有自己的授权。
我目前遇到的问题是:
由于每个用户都有不同的授权与之关联,我该如何遍历授权以打印出其下的所有地图。
敬请协助。
发布于 2018-08-27 19:17:18
您可以使用以下代码片段:
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);
});
});
});
}
不过,如果您不关心顺序,可以通过删除列表并只留下一个映射来简化“授权”字段:
"Entitlements": {
"GP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
},
"OPS": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
},
"IP": {
"Entitlement": "10000",
"Utilisation": "500",
"Balance": "9500"
}
}
发布于 2018-08-27 19:37:27
您在那里有信息:http://cogitas.net/parse-json-dart-flutter/
来自页面的示例:
void _parseJsonForCrossword(String jsonString) {
Map decoded = JSON.decode(jsonString);
String name = decoded['name'];
print(name);
int id = decoded['id'];
print(id.toString());
for (var word in decoded['across']) {
print(word['number'].toString());
print(word['word']);
}
}
https://stackoverflow.com/questions/52034895
复制相似问题