Is there a way to quickly check for null entries in decoded JSON object?
For example:
final responseJson = json.decode(response.body);
this returns the following:
responseJson['result']['mydata']['account'] = 'Joe Doe';
In order to check if 'mydata' part is not null, I have to do the following:
if(responseJson != null)
{
if(responseJson['result'] != null)
{
if(responseJson['result']['mydata'] != null)
...
which is really ugly. How to do it this way:
if((responseJson != null) && (responseJson['result'] != null) && (responseJson['result']['mydata'] != null))
{
}
In Dart this gives exception in case some of the middle item is null (i.e. ['result']).
There are null aware operators like:
obj?.method()
but how to use them with decoded JSON map object?
If you want to set a value like in
responseJson['result']['mydata']['account'] = 'Joe Doe';
this might work for you
data.putIfAbsent('result', () => {})
.putIfAbsent('mydata', () => {})
.putIfAbsent('account', () => 'John Doe');
For reading you can use
if(data.containsKey('result') && data['result'].containsKey('mydata')) {
data['result']['mydata']['account'] = 'Joe Doe';
} else {
print('empty');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With