我有一个JSON字符串
String str = '{ "name":"John", "age":31, "city":"New York" }'
Run Code Online (Sandbox Code Playgroud)
在上述字符串中,city是可选键,并且可能不存在于JSON数据中。
我解码了json字符串
var jsonResponse = json.decode(str);
Run Code Online (Sandbox Code Playgroud)
我想了解jsonResponse对象是否存在城市密钥。
我不确定解决方案有多好,但它正在起作用。
String str = '{ "name":"John", "age":31, "city":"New York" }';
Map<String, String> jsonResponse = json.decode(str);
if (jsonResponse.containsKey('city')){
// do your work
}
Run Code Online (Sandbox Code Playgroud)
不是在var中捕获 JSON 对象,而是将其捕获到一个
Map<String, String>
or
Map<String, Object> //if value is again an object
Run Code Online (Sandbox Code Playgroud)
的结果json.decode是Map<String, dynamic>带有源中每个键/值对的条目。
作为Map,您可以使用Map.containsKey测试键是否存在。您也可以使用"city"密钥进行查找,然后查看是否null返回。在某些情况下,null直接使用值比额外检查是否存在更方便,但这完全取决于您要做什么。
var map = jsonDecode(str);
bool containsCity = map.containsKey("city");
String city = map["city"];
if (city == null) // no city ...
// Use the null directly if you just replace it with a default.
print("${map["name"]} from ${map["city"] ?? "somewhere"}");
// Use a test if you want to do something different if it's there.
print(map["name"] + (city != null ? " from $city" : "");
Run Code Online (Sandbox Code Playgroud)
该map["city"] == null测试与map.containsKey("city")原始来源包含该对的情况不同"city": null。您需要决定这种情况是否会发生,如果发生了,您想如何对待它。在许多情况下,这可能是一个错误,应该被视为没有"city"条目,所以我通常更喜欢使用map["city"] == null测试而不是map.containsKey("city").
| 归档时间: |
|
| 查看次数: |
5421 次 |
| 最近记录: |