【问题标题】:How to access the index of a specific json key如何访问特定 json 键的索引
【发布时间】:2019-10-29 03:08:55
【问题描述】:

我需要访问特定的key来获取key为administrative_area_level_2administrative_area_level_1的节点信息。

我目前正在按索引“1”或“2”访问。

但如果来自 Google Api Places 的 json 结果有更多数据,则这些索引将不正确。

有什么方法可以访问我要捕获城市或州名的特定键吗?

示例代码:

class Api {

  pesquisar (String local) async{

    http.Response response = await http.get(

      URL_BASE + "?place_id=$local" +"&fields=name,address_component&key=" +KEY_PLACE

    );

    if( response.statusCode == HttpStatus.ok ){


      Map<String, dynamic> dadosJson = json.decode( response.body );
      print( "Data : " + dadosJson["result"]["address_components"][1]["short_name"].toString() );
      print( "Data : " + dadosJson["result"]["address_components"][2]["short_name"].toString() );

    } else {

    }


  }

}

【问题讨论】:

  • 如何循环结果并检查dadosJson["result"]["address_components"][i]["types"][0]是否为管理区域_1/管理区域_2

标签: json flutter dart google-places-api


【解决方案1】:

你可以这样做:

List components = dadosJson["result"]["address_components"];

final item1 = components.firstWhere(
    (item) => item["types"].contains("administrative_area_level_1"));

final item2 = components.firstWhere(
    (item) => item["types"].contains("administrative_area_level_1"));

print(item1["short_name"]);
print(item2["short_name"]);

或者

List components = dadosJson["result"]["address_components"];

final items = components
    .where((item) =>
        item["types"].contains("administrative_area_level_1") ||
        item["types"].contains("administrative_area_level_2"))
    .toList();

items.forEach((item) => print(item["short_name"]));

我建议你将json解析成对象模型,这样你就不必面对一些类型推断的问题了。

【讨论】:

  • 您好,它不工作。错误:类型“(动态)=>动态”不是“测试”类型“(动态)=>布尔”的子类型。地图上的变量 DYNAMIC 是否有任何问题。 @PabloBarrera
  • 仍然有同样的错误:'(Map>) => bool' 不是'test' 的'(dynamic) => bool' 类型的子类型。 @PabloBarrera
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 2017-06-07
  • 2021-03-29
相关资源
最近更新 更多