Search code examples
jsonflutterdartfromjson

Get object in json flutter


I have this JSON output (using Chopper library)

{"status":"success","error_message":[],"abc":[{"id":"124"},{"id":"125"}]}

How can I get the id in object abc ?

Response response = await _repo.submitData(title, description);

var abcResponse = ABCResponse.fromJson(response.body);
    if (abcResponse.status == 'success') {
       // I want print the latest id
  }
}

ABCResponse

part 'abc_response.g.dart';

    @JsonSerializable()
    class ABCResponse extends BaseResponse {
      var abc = new List<ABC>();
      ABCResponse();

      factory ABCResponse.fromJson(Map<String, dynamic> json) =>
          _$ABCResponse(json);
      Map<String, dynamic> toJason() => _$WABCResponseToJson(this);
    }

ABC

 @JsonSerializable()
class ABC {

  ABC();
  var id;
}

Edit

 Response response = await _repository.submitData(title, description);

    var abcResponse = ABCResponse.fromJson(response.body);
    if (abcResponse.status == 'success') {
      var user = json.decode(abcResponse.abc.toString());
      print(user);   // it printing null value
    }

Solution

  • Here is an example code to decode the given json and extract id.

    import 'dart:convert';
    
    void main() 
    {
      var jsonString = '{"status":"success","error_message":[],"abc":[{"id":"124"},{"id":"125"}]}'; // just store input json to a variable.
      var user = json.decode(jsonString.toString()); // convert input to string if it isn't already
      print(user['abc'][0]['id']); // complex(nested) json parsing; prints 124
    }
    

    use json.decode() to convert json string to a Map.

    1. user['abc'] will give you [{id: 124}, {id: 125}]
    2. user['abc'][0] will give you {id: 124}, {id: 125} i.e. extract 0th element of the input List.
    3. Finally ['abc'][0]['id'] will give you the id: 124.