Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null checks after json.decode

Tags:

flutter

dart

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?

like image 933
Andrew Avatar asked Dec 17 '25 23:12

Andrew


1 Answers

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');
  }
like image 152
Günter Zöchbauer Avatar answered Dec 20 '25 18:12

Günter Zöchbauer