json dart code example
Example 1: flutter generate json files
flutter packages pub run build_runner build
Example 2: parse json to dart model
import 'dart:convert';
main() {
String nestedObjText =
'{"title": "Dart Tutorial", "description": "Way to parse Json", "author": {"name": "bezkoder", "age": 30}}';
Tutorial tutorial = Tutorial.fromJson(jsonDecode(nestedObjText));
print(tutorial);
Example 3: json to dart
class Autogenerated {
int postId;
int id;
String name;
String email;
String body;
Autogenerated({this.postId, this.id, this.name, this.email, this.body});
Autogenerated.fromJson(Map<String, dynamic> json) {
postId = json['postId'];
id = json['id'];
name = json['name'];
email = json['email'];
body = json['body'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['postId'] = this.postId;
data['id'] = this.id;
data['name'] = this.name;
data['email'] = this.email;
data['body'] = this.body;
return data;
}
}
Example 4: json to dart
class BusinessProfileEditModel {
String name;
String address;
String email;
String phoneNumber;
String rcNumber;
String businessRegistrationTypeKey;
String businessVerticalKey;
String countryKey;
String lgaKey;
BusinessProfileEditModel(
{this.name,
this.address,
this.email,
this.phoneNumber,
this.rcNumber,
this.businessRegistrationTypeKey,
this.businessVerticalKey,
this.countryKey,
this.lgaKey});
BusinessProfileEditModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
address = json['address'];
email = json['email'];
phoneNumber = json['phoneNumber'];
rcNumber = json['rcNumber'];
businessRegistrationTypeKey = json['businessRegistrationTypeKey'];
businessVerticalKey = json['businessVerticalKey'];
countryKey = json['countryKey'];
lgaKey = json['lgaKey'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['address'] = this.address;
data['email'] = this.email;
data['phoneNumber'] = this.phoneNumber;
data['rcNumber'] = this.rcNumber;
data['businessRegistrationTypeKey'] = this.businessRegistrationTypeKey;
data['businessVerticalKey'] = this.businessVerticalKey;
data['countryKey'] = this.countryKey;
data['lgaKey'] = this.lgaKey;
return data;
}
}