Dart json.decode后的空检查
有没有办法快速检查解码的JSON对象中的空条目 例如:Dart json.decode后的空检查,dart,flutter,Dart,Flutter,有没有办法快速检查解码的JSON对象中的空条目 例如: final responseJson = json.decode(response.body); 这将返回以下内容: responseJson['result']['mydata']['account'] = 'Joe Doe'; if(responseJson != null) { if(responseJson['result'] != null) {
final responseJson = json.decode(response.body);
这将返回以下内容:
responseJson['result']['mydata']['account'] = 'Joe Doe';
if(responseJson != null)
{
if(responseJson['result'] != null)
{
if(responseJson['result']['mydata'] != null)
...
为了检查“mydata”部分是否为空,我必须执行以下操作:
responseJson['result']['mydata']['account'] = 'Joe Doe';
if(responseJson != null)
{
if(responseJson['result'] != null)
{
if(responseJson['result']['mydata'] != null)
...
这真的很难看。如何这样做:
if((responseJson != null) && (responseJson['result'] != null) && (responseJson['result']['mydata'] != null))
{
}
在Dart中,如果中间的某些项为空(即,['result']),则会出现异常
有空感知运算符,如:
obj?.method()
但是如何将它们与解码的JSON映射对象一起使用呢?如果您想设置一个类似
responseJson['result']['mydata']['account'] = 'Joe Doe';
这可能对你有用
data.putIfAbsent('result', () => {})
.putIfAbsent('mydata', () => {})
.putIfAbsent('account', () => 'John Doe');
对于阅读,你可以使用
if(data.containsKey('result') && data['result'].containsKey('mydata')) {
data['result']['mydata']['account'] = 'Joe Doe';
} else {
print('empty');
}
您应该做的不是直接使用JSON对象,而是将其转换为Dart类。然后使用空感知运算符
final response = new Response.fromJSON(json.decode(''));
if (response?.result?.myData != null) {
}
您可以使用json\u serializable
或build\u value
从json类构造函数生成
或者您可以手动编写它们:
class Data {
String account;
Data.fromJSON(Map json) {
if (json.containsKey('myData')) {
account = json['myData'];
}
}
}
class Result {
Data myData;
Result({this.myData});
Result.fromJSON(Map json) {
if (json.containsKey('myData')) {
myData = json['myData'];
}
}
}
class Response {
Result result;
Response({this.result});
Response.fromJSON(Map json) {
if (json.containsKey('result')) {
result = json['result'];
}
}
}
第二个例子中有什么例外?如果前面的表达式失败,Dart应该短路,并且不计算下面的&&&…
表达式。我也希望如此,但事实并非如此。在这种情况下,它不像其他语言那样短路。如果['result']为null,它会抱怨从null请求['mydata']。如果条目的显式值为null
,则可能会添加一条注释,说明这不起作用(但是,如果值也是字符串,则也不起作用)。谢谢,我认为containsKey()是我需要的。与刚才的(somevar['key']!=null)相比,它是“短路”的。谢谢您的建议。为了简单起见,我将尝试使用“if(data.containsKey('result')&&data['result'].containsKey('mydata'))”。