检查多维json响应[Flutter][Dart]中是否存在密钥



我正在从http端点读取一些json数据,并继续处理如下结果:

var decodedResponse = json.decode(response.body);
if(decodedResponse['ingredients']['additives'] != null) {
getAdditiveList = await getAdditiveNames(decodedResponse['ingredients']['additives']);
decodedResponse['ingredients']['additives'] = getAdditiveList;
}

由于有时"additions"甚至"components"键都不是json响应的一部分,因此我得到以下错误:

[VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("additives")

我认为以下在技术上可以作为验证,但这看起来不是一个好主意:

if(decodedResponse.containsKey("ingredients")){
if(decodedResponse['ingredients'].containsKey("additives")){
}
}

任何帮助都将不胜感激!谢谢

看起来有时您的decodeResponse值为null。你应该这样检查:

if(decodedResponse != null && decodedResponse['ingredients'] != null && decodedResponse['ingredients']['additives'] != null){}

像这样,你会一直检查它是否有一个值,因为它会像你从API的响应有时会给你空。

最新更新