How to convert Response JSON to Object in Flutter? How to convert Response JSON to Object in Flutter? dart dart

How to convert Response JSON to Object in Flutter?


Don't need to use cast, you can parse directly to a Map

final Map parsed = json.decode(res); 

After you have a map you can use that data to convert into your Object.

final signUp = SignUpResponse.fromJson(parsed);

And if you want to parse an array of objects, you could do something like this:

//assuming this json returns an array of signupresponse objectsfinal List parsedList = json.decode(res); List<SignUpResponse> list = parsedList.map((val) =>  SignUpResponse.fromJson(val)).toList();


The JSON :

    [     {       "id":1,       "name":"Afghanistan",       "iso3":"AFG",       "iso2":"AF",       "phone_code":"93",       "capital":"Kabul",       "currency":"AFN"     },     {       "id":2,       "name":"Aland Islands",       "iso3":"ALA",       "iso2":"AX",       "phone_code":"+358-18",       "capital":"Mariehamn",       "currency":"EUR"       },    ]

The POJO Class :

    class country{       String id;       String name;       String currency;       country({this.id,this.name,this.currency});       factory country.fromJson(Map<String, dynamic> parsedJson){         return country(         id: parsedJson['id'].toString(),         name : parsedJson['name'].toString(),         currency: parsedJson['currency'].toString()          );       }    }

API CALL :

    await http.post("http://calikidsmap.com/test.php").then((response){    var ddd=jsonDecode(response.body);    Country_object_list = (ddd as List)      .map((data) => new country.fromJson(data))      .toList();


Same answer but, what happens when you have nested JsonObjects?Easy:

Given a jsonResponse like this:

{  "id": 1,  "type": 15,  "innerClass": {    "id": 1,    "type": "testing"  }}

This is an example of how the code looks like:

class MainClass {  int id = 0;  int version = 0;  InnerClass innerClass;  MainClass (      this.id,      this.version,      this.innerClass      );  //Create the same factory converter, but using another inner factory 'fromJson' converter//for the inner class object (InnerClass.fromJson(json['inner_class']))  factory MainClass.fromJson(dynamic json) {    return MainClass(        json['id'] as int, // << put your json response keys instead.        json['version'] as int,        InnerClass.fromJson(json['innerClass']) // << this one    );  }

Then, repeat the same strategy but for the inner class object:

class InnerClass {  int id = 0;  String type = 'testing_type';  InnerClass (      this.id,      this.type      );  factory InnerClass.fromJson(dynamic json) {    return InnerClass(        json['id'] as int,        json['type'] as String    );  }}

Finally, you could cosume that, in another part of you project like this:

try {          mainClassDartObject = MainClass.fromJson(response.body);     } catch (e) {          print(e);     }