json - 如何循环 Json 数据?
问题描述
这是我的 json 结构。
[
[
{
"nos": 0,
"name": "A S MUSIC AND DANCE A CULTURAL ORGANIZATION",
"unique_id": "AN/2020/0259067",
"reg_details": [
{
"registered_with": "Registrar of Societies"
},
{
"type_of_ngo": "Registered Societies (Non-Government)"
这工作正常。
String jsonString = await _loadANgoAsset();
final jsonResponse = json.decode(jsonString);
String name = jsonResponse[0][0]['name'];
debugPrint("Name of NGO is $name");
但是,当我想使用此代码循环遍历各种数据实体的键时:
List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];
allNamesOfNGO.forEach((allNamesOfNGO) {
(allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
print(key);
(value as Map<String, dynamic>).forEach((key2, value2) {
print(key2);
print(value2);
});
});
});
出现以下错误:
E/flutter ( 4683): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'
请帮忙!
解决方案
List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];
此行尝试将第一个 ngo(String) 的名称分配给 allNamesOfNGO(List),从而导致上述错误。要克服此错误,请将上面的代码替换为:
List<dynamic> allNamesOfNGO = jsonResponse[0];
allNamesOfNGO.forEach((allNamesOfNGO) {
(allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
print(key);
print(value);
if(key == "reg_details") {
value.forEach(regDetail) {
print(regDetail);
});
}
});
});
您不需要最里面的 forEach 循环,因为您已经在该循环之前获得了键值对。在最里面的 forEach 循环中,您尝试遍历单个键,例如 nos、name 和 unique_is(它是字符串或 int),这是不可能的。reg_details的值是一个列表。所以你可以循环遍历它,但为此你必须检查 if key == "reg_details"
。
推荐阅读
- spring-boot - 找不到类型类 org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap 的 PersistentEntity
- flutter - Dart 使用转义字符解码 JSON API 响应
- reactjs - React + react-intersection-observer -- 无法设置新的 `options.root`
- excel - Datatables.js excel 导出保存为切诺基货币
- apache-spark - 检查表是否存在:Spark bigquery 连接器
- facebook - 如何获取 facebook api 中评论的真实计数
- spring-boot - Spring Cloud Data Flow,未能按照 HTTP 到 MySQL Demo
- python - 如何标记文本语料库?
- angular - 角 | 使用 httpInterceptor 迟到的错误响应
- r - 使用查找表替换部分字符串