Reputation: 37
I'm trying to parse JSON to an object in Dart, the documentation uses Map type to parse a JSON response.I have about 200 list on data form json file.
My result data to list of all record and render it to ListView in flutter. I have push code in github. https://github.com/phuochoit/user_list
[
id,
name,
username,
email,
phone
]
JSON
{
"type": "user",
"format": "json",
"version": "1.0",
"data": {
"[email protected]": {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
"[email protected]": {
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "[email protected]",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
.... to be continued
}
}
I have code get json file and decode it in dart but i not map data to render
Future<UserModel> fetchUser() async {
final response = await http.get('http://172.16.0.2/data/users.json');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return UserModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
Upvotes: 1
Views: 3117
Reputation: 17567
Compare this with things like quicktype: (1) If you do not have a model class, then try to use things like quicktype to get that class from a sample json string. (2) However, I suggest not to use the toJson
and fromJson
given by quicktype. The reason is that, when your model changes (say add a field / change a field), you must also change your toJson/fromJson accordingly (which is time-consuming and error-prone). Otherwise you get a bug.
If you already have your model class and only need the toJson
and fromJson
methods: Then the very famous json_serializable package suits you. It will happily generate the toJson
and fromJson
.
For example, say you have
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
}
Then with a bit of boilerplate code, it will auto give you
Person _$PersonFromJson(Map<String, dynamic> json) {
return Person(
firstName: json['firstName'] as String,
lastName: json['lastName'] as String,
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String),
);
}
Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
'firstName': instance.firstName,
'lastName': instance.lastName,
'dateOfBirth': instance.dateOfBirth.toIso8601String(),
};
Actually that package is more powerful than that. Check out the link for more details.
Upvotes: 1
Reputation: 19134
I recommend using a JSON model generator, don't waste your time in reinventing the wheel.
I used https://app.quicktype.io/ it's awesome, input JSON, it will create Dart classes, piece of cake, really!
For example for this JSON :
[{
"_id": {
"$oid": "5968dd23fc13ae04d9000001"
},
"product_name": "sildenafil citrate",
"supplier": "Wisozk Inc",
"quantity": 261,
"unit_cost": "$10.47"
}, {
"_id": {
"$oid": "5968dd23fc13ae04d9000002"
},
"product_name": "Mountain Juniperus ashei",
"supplier": "Keebler-Hilpert",
"quantity": 292,
"unit_cost": "$8.74"
}, {
"_id": {
"$oid": "5968dd23fc13ae04d9000003"
},
"product_name": "Dextromathorphan HBr",
"supplier": "Schmitt-Weissnat",
"quantity": 211,
"unit_cost": "$20.53"
}]
It generated this model in Dart:
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));
String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Welcome {
Welcome({
this.id,
this.productName,
this.supplier,
this.quantity,
this.unitCost,
});
Id id;
String productName;
String supplier;
int quantity;
String unitCost;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
id: Id.fromJson(json["_id"]),
productName: json["product_name"],
supplier: json["supplier"],
quantity: json["quantity"],
unitCost: json["unit_cost"],
);
Map<String, dynamic> toJson() => {
"_id": id.toJson(),
"product_name": productName,
"supplier": supplier,
"quantity": quantity,
"unit_cost": unitCost,
};
}
class Id {
Id({
this.oid,
});
String oid;
factory Id.fromJson(Map<String, dynamic> json) => Id(
oid: json["\u0024oid"],
);
Map<String, dynamic> toJson() => {
"\u0024oid": oid,
};
}
Upvotes: 2