How to convert Response JSON to Object in Flutter?
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);
}
Here is a basic answer for this if you want to access your information after the request with no extra steps.
Map<String, dynamic> data = jsonDecode(response.body);
String token = data["data"]["access_token"];
the structure of the object from the request was like this:
{
"success":1,
"error":[],
"data": {
"access_token":"13d2ec9d1094903b1e81de8af059233e9f36ec4d",
"expires_in":2628000,
"token_type":"Bearer"
}
}
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 objects
final 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();