Reputation: 121
Following is my json output
{
"success": true,
"data": {
"id": 1,
"username": "MV",
"name": "Saraa",
"userSponsorData": {
"initial": "GT",
"name": "Green Trust",
"email": "[email protected]",
"username": "trust",
"phone": "1234567890"
}
}
}
Following is part of my model dart file
class UserDetailModel {
bool success;
Data data;
UserDetailModel({this.success, this.data});
UserDetailModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
}
By parsing I am able to get the values under jsonObject "data", the values are able to be printed
class Data {
String name;
String email;
String uname;
String phone;
SponsorData sData;
Data({this.name, this.email, this.uname, this.phone, this.sData});
Data.fromJson(Map<String, dynamic> json) {
name = json['name'];
email = json['email'];
uname = json['username'];
phone = json['phone'];
sData = json['userSponsorData'] != null
? new SponsorData.fromJson(json['userSponsorData'])
: null;
}
}
but not able to retrieve from jsonObject "userSponsorData" - while i try to print the values,
NoSuchMethodError: The getter 'initial' was called on null. - how to fix this
Upvotes: 0
Views: 129
Reputation: 864
void main() {
var value = {
"success": true,
"data": {
"id": 1,
"username": "MV",
"name": "Saraa",
"userSponsorData": {
"initial": "GT",
"name": "Green Trust",
"email": "[email protected]",
"username": "trust",
"phone": "1234567890"
}
}
};
new Data.fromJson(value['data']);
}
class Data {
String name;
String email;
String uname;
String phone;
SponsorData sData;
Data({this.name, this.email, this.uname, this.phone, this.sData});
Data.fromJson(Map<String, dynamic> json) {
name = json['name'];
email = json['email'];
uname = json['username'];
phone = json['phone'];
sData = json['userSponsorData'] != null
? new SponsorData.fromJson(json['userSponsorData'])
: null;
}
}
class SponsorData {
String sdata;
SponsorData({this.sdata});
SponsorData.fromJson(Map<String, dynamic> json) {
var initial = json['initial'];
var name = json['name'];
var email = json['email'];
var username = json['username'];
var phone = json['phone'];
print("$initial , $name , $email");
}
}
sucess result
Upvotes: 1