i have a PODO created for my model. See below:
class Data {
String? parentWo;
String? parentWoDesc;
String? parentWoStatus;
String? parentWoStatusDate;
String? parentWoWorkType;
String? parentWoClass;
String? parentWoCrew;
String? parentWoLead;
String? parentWoLocation;
String? parentWoDepartmentDescription;
String? parentWoSectionDescription;
List<Child>? children;
Data({
this.parentWo,
this.parentWoDesc,
this.parentWoStatus,
this.parentWoStatusDate,
this.parentWoWorkType,
this.parentWoClass,
this.parentWoCrew,
this.parentWoLead,
this.parentWoLocation,
this.parentWoDepartmentDescription,
this.parentWoSectionDescription,
this.children,
});
factory Data.fromJson(Map<String, dynamic> json) {
var list = json['children'] as List;
print(list.runtimeType);
List<Child> childrenlist = list.map((i) => Child.fromJson(i)).toList();
return Data(
parentWo: json["parentWo"] ?? 'VADER',
parentWoDesc: json["parentWoDesc"],
parentWoStatus: json["parentWoStatus"],
parentWoStatusDate: json["parentWoStatusDate"],
parentWoWorkType: json["parentWoWorkType"],
parentWoClass: json["parentWoClass"],
parentWoCrew: json["parentWoCrew"],
parentWoLead: json["parentWoLead"],
parentWoLocation: json["parentWoLocation"],
parentWoDepartmentDescription: json["parentWoDepartmentDescription"],
parentWoSectionDescription: json["parentWoSectionDescription"],
children:
childrenlist,
);
}
Map<String, dynamic> toJson() => {
"parentWo": parentWo,
"parentWoDesc": parentWoDesc,
"parentWoStatus": parentWoStatus,
"parentWoStatusDate": parentWoStatusDate,
"parentWoWorkType": parentWoWorkType,
"parentWoClass": parentWoClass,
"parentWoCrew": parentWoCrew,
"parentWoLead": parentWoLead,
"parentWoLocation": parentWoLocation,
"parentWoDepartmentDescription": parentWoDepartmentDescription,
"parentWoSectionDescription": parentWoSectionDescription,
"children": List<dynamic>.from(children!.map((x) => x.toJson())),
};
}
class Child {
String? woNum;
String? woDesc;
String? woStatus;
DateTime? woStatusDate;
String? woCrew;
String? woLead;
String? woLocation;
List<Materials>? materials;
Child({
this.woNum,
this.woDesc,
this.woStatus,
this.woStatusDate,
this.woCrew,
this.woLead,
this.woLocation,
this.materials,
});
factory Child.fromJson(Map<String, dynamic> json) {
var list = json['materials'] as List;
print(list.runtimeType);
List<Materials> materialslist = list.map((i) => Materials.fromJson(i)).toList();
return Child(
woNum: json["woNum"],
woDesc: json["woDesc"],
woStatus: json["woStatus"],
woStatusDate: DateTime.parse(json["woStatusDate"]),
woCrew: json["woCrew"],
woLead: json["woLead"],
woLocation: json["woLocation"],
materials: materialslist,
);
}
Map<String, dynamic> toJson() => {
"woNum": woNum,
"woDesc": woDesc,
"woStatus": woStatus,
"woStatusDate": woStatusDate!.toIso8601String(),
"woCrew": woCrew,
"woLead": woLead,
"woLocation": woLocation,
"materials": List<dynamic>.from(materials!.map((x) => x.toJson())),
};
get length => null;
}
class Materials {
String? itemNum;
String? itemDescription;
int? itemQuantityPlan;
int? itemQuantityIssued;
int? itemWoBalance;
int? itemInventoryBalance;
String? itemCommodity;
String? itemIssueUnit;
bool? itemStructure;
bool? itemDtPole;
Materials({
this.itemNum,
this.itemDescription,
this.itemQuantityPlan,
this.itemQuantityIssued,
this.itemWoBalance,
this.itemInventoryBalance,
this.itemCommodity,
this.itemIssueUnit,
this.itemStructure,
this.itemDtPole,
});
factory Materials.fromJson(Map<String, dynamic> json) => Materials(
itemNum: json["itemNum"],
itemDescription: json["itemDescription"],
itemQuantityPlan: json["itemQuantityPlan"],
itemQuantityIssued: json["itemQuantityIssued"],
itemWoBalance: json["itemWoBalance"],
itemInventoryBalance: json["itemInventoryBalance"],
itemCommodity: json["itemCommodity"],
itemIssueUnit: json["itemIssueUnit"],
itemStructure: json["itemStructure"],
itemDtPole: json["itemDtPole"],
);
Map<String, dynamic> toJson() => {
"itemNum": itemNum,
"itemDescription": itemDescription,
"itemQuantityPlan": itemQuantityPlan,
"itemQuantityIssued": itemQuantityIssued,
"itemWoBalance": itemWoBalance,
"itemInventoryBalance": itemInventoryBalance,
"itemCommodity": itemCommodity,
"itemIssueUnit": itemIssueUnit,
"itemStructure": itemStructure,
"itemDtPole": itemDtPole,
};
#override
String toString() {
// TODO: implement toString
return '$itemNum';
}
}
Now i'm having a hard time parsing the jsonresponse i got from the api. here's what i got (see comments on the code lines):
Future loadParent2() async {
Map data = {'wonum': WOInputted};
var bodyy = json.encode(data);
var jsonString = await http.post(
Uri.parse("https://sample.com.ph/extension/list/"),
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer $getAccessToken'
},
body: bodyy);
final jsonResponse = jsonDecode(jsonString.body);
final valueResponse = jsonResponse['results']['status_code'];
if (jsonString.statusCode == 200 && valueResponse == '1') {
print('NO RESULTS IN PARENT WO');
print('VALUE RESPONSE: $valueResponse');
} else if (jsonString.statusCode == 200 && valueResponse == '0') {
print('THIS HAVE RESULTS IN PARENT WO');
print('VALUE RESPONSE: $valueResponse');
sampleParentWO = jsonResponse['results']['data']['parentWo'];
final parentWOResponse = jsonResponse['results']['data'];
print(parentWOResponse); //CAN PRINT THIS RESPONSE, MEANING I GOT A RIGHT RESPONSE
Data dataPick = new Data.fromJson(parentWOResponse); //NOT SURE IF JSON RESPONSE IS SAVING TO MY MODEL PODO
print(dataPick.parentWo); //WHEN I TRY TO PRINT THIS THERE'S NO OUTPUT
mainParentPick = Data.fromJson(parentWOResponse);
print(mainParentPick.parentWo); //TRIED THIS BUT STILL NO OUTPUT
print(mainParentPick); //NO OUTPUT
return mainParentPick;
}
else {
throw Exception('Failed there\'s an error');
}
}
What am I missing here? do i need to do something else?
Hope someone helps me and point to the right direction.
Thank you for your time.
You can use json to dart online tools or can add plugin to Android Studio
One of dart generator online tool - Json Formatter Online Tool
Android Studio Plugin Json2Dart Plugin
There is casting error with your json response and response model
In your model, Type cast using Int.
int? itemQuantityPlan;
int? itemQuantityIssued;
int? itemWoBalance;
In your Response, There is double
"itemQuantityPlan": 1.0,
"itemQuantityIssued": 42.0,
"itemWoBalance": -41.0,
"itemInventoryBalance": -2602.47,
I have created a dart model by your Api response from here :
class ApiResponseModel {
Results? results;
ApiResponseModel({this.results});
ApiResponseModel.fromJson(Map<String, dynamic> json) {
results =
json['results'] != null ? new Results.fromJson(json['results']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.results != null) {
data['results'] = this.results!.toJson();
}
return data;
}
}
class Results {
Data? data;
String? statusCode;
String? statusMsg;
Results({this.data, this.statusCode, this.statusMsg});
Results.fromJson(Map<String, dynamic> json) {
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
statusCode = json['status_code'];
statusMsg = json['status_msg'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.toJson();
}
data['status_code'] = this.statusCode;
data['status_msg'] = this.statusMsg;
return data;
}
}
class Data {
String? parentWo;
String? parentWoDesc;
String? parentWoStatus;
String? parentWoStatusDate;
String? parentWoWorkType;
String? parentWoClass;
String? parentWoCrew;
String? parentWoLead;
String? parentWoLocation;
String? parentWoDepartmentDescription;
String? parentWoSectionDescription;
List<Children>? children;
Data(
{this.parentWo,
this.parentWoDesc,
this.parentWoStatus,
this.parentWoStatusDate,
this.parentWoWorkType,
this.parentWoClass,
this.parentWoCrew,
this.parentWoLead,
this.parentWoLocation,
this.parentWoDepartmentDescription,
this.parentWoSectionDescription,
this.children});
Data.fromJson(Map<String, dynamic> json) {
parentWo = json['parentWo'];
parentWoDesc = json['parentWoDesc'];
parentWoStatus = json['parentWoStatus'];
parentWoStatusDate = json['parentWoStatusDate'];
parentWoWorkType = json['parentWoWorkType'];
parentWoClass = json['parentWoClass'];
parentWoCrew = json['parentWoCrew'];
parentWoLead = json['parentWoLead'];
parentWoLocation = json['parentWoLocation'];
parentWoDepartmentDescription = json['parentWoDepartmentDescription'];
parentWoSectionDescription = json['parentWoSectionDescription'];
if (json['children'] != null) {
children = <Children>[];
json['children'].forEach((v) {
children!.add(new Children.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['parentWo'] = this.parentWo;
data['parentWoDesc'] = this.parentWoDesc;
data['parentWoStatus'] = this.parentWoStatus;
data['parentWoStatusDate'] = this.parentWoStatusDate;
data['parentWoWorkType'] = this.parentWoWorkType;
data['parentWoClass'] = this.parentWoClass;
data['parentWoCrew'] = this.parentWoCrew;
data['parentWoLead'] = this.parentWoLead;
data['parentWoLocation'] = this.parentWoLocation;
data['parentWoDepartmentDescription'] = this.parentWoDepartmentDescription;
data['parentWoSectionDescription'] = this.parentWoSectionDescription;
if (this.children != null) {
data['children'] = this.children!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Children {
String? woNum;
String? woDesc;
String? woStatus;
String? woStatusDate;
String? woCrew;
String? woLead;
String? woLocation;
List<Materials>? materials;
Children(
{this.woNum,
this.woDesc,
this.woStatus,
this.woStatusDate,
this.woCrew,
this.woLead,
this.woLocation,
this.materials});
Children.fromJson(Map<String, dynamic> json) {
woNum = json['woNum'];
woDesc = json['woDesc'];
woStatus = json['woStatus'];
woStatusDate = json['woStatusDate'];
woCrew = json['woCrew'];
woLead = json['woLead'];
woLocation = json['woLocation'];
if (json['materials'] != null) {
materials = <Materials>[];
json['materials'].forEach((v) {
materials!.add(new Materials.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['woNum'] = this.woNum;
data['woDesc'] = this.woDesc;
data['woStatus'] = this.woStatus;
data['woStatusDate'] = this.woStatusDate;
data['woCrew'] = this.woCrew;
data['woLead'] = this.woLead;
data['woLocation'] = this.woLocation;
if (this.materials != null) {
data['materials'] = this.materials!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Materials {
String? itemNum;
String? itemDescription;
double? itemQuantityPlan;
int? itemQuantityIssued;
double? itemWoBalance;
double? itemInventoryBalance;
String? itemCommodity;
String? itemIssueUnit;
bool? itemStructure;
bool? itemDtPole;
Materials(
{this.itemNum,
this.itemDescription,
this.itemQuantityPlan,
this.itemQuantityIssued,
this.itemWoBalance,
this.itemInventoryBalance,
this.itemCommodity,
this.itemIssueUnit,
this.itemStructure,
this.itemDtPole});
Materials.fromJson(Map<String, dynamic> json) {
itemNum = json['itemNum'];
itemDescription = json['itemDescription'];
itemQuantityPlan = json['itemQuantityPlan'];
itemQuantityIssued = json['itemQuantityIssued'];
itemWoBalance = json['itemWoBalance'];
itemInventoryBalance = json['itemInventoryBalance'];
itemCommodity = json['itemCommodity'];
itemIssueUnit = json['itemIssueUnit'];
itemStructure = json['itemStructure'];
itemDtPole = json['itemDtPole'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['itemNum'] = this.itemNum;
data['itemDescription'] = this.itemDescription;
data['itemQuantityPlan'] = this.itemQuantityPlan;
data['itemQuantityIssued'] = this.itemQuantityIssued;
data['itemWoBalance'] = this.itemWoBalance;
data['itemInventoryBalance'] = this.itemInventoryBalance;
data['itemCommodity'] = this.itemCommodity;
data['itemIssueUnit'] = this.itemIssueUnit;
data['itemStructure'] = this.itemStructure;
data['itemDtPole'] = this.itemDtPole;
return data;
}
}
Step 2 : create function for calling api
Future<http.Response> getResponse(Map<String, String> request) async {
final response =
await http.post(Uri.parse(BASE_URL + "urlapilink"), body: request.toJson());
return response;
}
step 3 : get response from api :
ApiResponseModel apiResponseModel ;
getResponseFromApi(){
Map request = {'wonum': WOInputted};
getFirmDetails(request).then((value){
if(value.statusCode==200){
apiResponseModel = ApiResponseModel.fromJson(value.body);
}
});
}
i was trying get this apical l but this exceptions occurs
Unhanded Exception: type 'String' is not a sub type of type 'Map<String, dynamic>',somebody please explain why this occurs,or re edit the code .if you could explain how to handle to get data would be really helpful,
flutter appi response error
class Repo {
Future<List<Modelclass>?> getdata() async {
List<Modelclass> collections = [];
final response = await http.get(Uri.parse(url));
if (response.statusCode != 200) {
return null;
} else {
Map<String, dynamic> data = jsonDecode(response.body);
for (var i in data.values) {
Modelclass modelclass = Modelclass.fromJson(i);
collections.add(modelclass);
}
return collections;
}
}
}
modelclass.dart
Time? time;
String? disclaimer;
String? chartName;
Bpi? bpi;
Modelclass({this.time, this.disclaimer, this.chartName, this.bpi});
Modelclass.fromJson(Map<String, dynamic> json) {
time = json['time'] != null ? new Time.fromJson(json['time']) : null;
disclaimer = json['disclaimer'];
chartName = json['chartName'];
bpi = json['bpi'] != null ? new Bpi.fromJson(json['bpi']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.time != null) {
data['time'] = this.time!.toJson();
}
data['disclaimer'] = this.disclaimer;
data['chartName'] = this.chartName;
if (this.bpi != null) {
data['bpi'] = this.bpi!.toJson();
}
return data;
}
}
class Time {
String? updated;
String? updatedISO;
String? updateduk;
Time({this.updated, this.updatedISO, this.updateduk});
Time.fromJson(Map<String, dynamic> json) {
updated = json['updated'];
updatedISO = json['updatedISO'];
updateduk = json['updateduk'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['updated'] = this.updated;
data['updatedISO'] = this.updatedISO;
data['updateduk'] = this.updateduk;
return data;
}
}
class Bpi {
USD? uSD;
USD? gBP;
USD? eUR;
Bpi({this.uSD, this.gBP, this.eUR});
Bpi.fromJson(Map<String, dynamic> json) {
uSD = json['USD'] != null ? new USD.fromJson(json['USD']) : null;
gBP = json['GBP'] != null ? new USD.fromJson(json['GBP']) : null;
eUR = json['EUR'] != null ? new USD.fromJson(json['EUR']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.uSD != null) {
data['USD'] = this.uSD!.toJson();
}
if (this.gBP != null) {
data['GBP'] = this.gBP!.toJson();
}
if (this.eUR != null) {
data['EUR'] = this.eUR!.toJson();
}
return data;
}
}
class USD {
String? code;
String? symbol;
String? rate;
String? description;
double? rateFloat;
USD({this.code, this.symbol, this.rate, this.description, this.rateFloat});
USD.fromJson(Map<String, dynamic> json) {
code = json['code'];
symbol = json['symbol'];
rate = json['rate'];
description = json['description'];
rateFloat = json['rate_float'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
data['symbol'] = this.symbol;
data['rate'] = this.rate;
data['description'] = this.description;
data['rate_float'] = this.rateFloat;
return data;
}
}
main.dart
child: Container(
child: Text(state.modelclass[2].time.toString() )```
as i can in your code in Repo class you are write something like this - Modelclass modelclass = Modelclass.fromJson(i) in which i is Iterable<dynamic> while in your modelclass.dart Modelclass.fromJson(Map<String, dynamic> json) requirement is Map.
If you still face this issue then please specify on which line number you are getting error, it will help.
My first project and newbie to flutter, unable to solve this after 2 weeks of trying.
I am trying to get request via API using GetX package and i got the error mentioned above.
Trying to parse JsonMap into a List and it's giving me the error mentioned.
I have tested and the StatusCode is 200, I am assuming its just not parsing correctly.
Thanks in advance!
Peace
JY
Error message: -
Error: Expected a value of type '(String, dynamic) => void', but got one of type '(dynamic) => Null'
Controller:-
class BlogController extends GetxController {
final BlogRepo blogRepo;
BlogController({required this.blogRepo});
List<dynamic> _blogList = [];
List<dynamic> get blogList => _blogList;
Future<void> getBlogList() async {
Response response = await blogRepo.getBlogList();
if (response.statusCode == 200) {
print("Got Data"); //this gets printed
_blogList = [];
_blogList.addAll(Blog.fromJson(response.body).data);
print(_blogList); // not printing _blogList
update();
} else {}
}
}
Model:-
class Blog {
late List<Data> _data;
List<Data> get data => _data;
Blog({required data}) {
this._data = data;
}
Blog.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
_data = <Data>[];
json['data'].forEach(
(v) {
_data.add(Data.fromJson(v));
},
);
}
}
}
class Data {
int? id;
Attributes? attributes;
Data({this.id, this.attributes});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
attributes = json['attributes'] != null
? Attributes.fromJson(json['attributes'])
: null;
}
}
class Attributes {
String? title;
String? createdAt;
String? updatedAt;
String? publishedAt;
String? text;
String? link;
Image? image;
Attributes(
{this.title,
this.createdAt,
this.updatedAt,
this.publishedAt,
this.text,
this.link,
this.image});
Attributes.fromJson(Map<String, dynamic> json) {
title = json['title'];
createdAt = json['createdAt'];
updatedAt = json['updatedAt'];
publishedAt = json['publishedAt'];
text = json['text'];
link = json['link'];
image = json['image'] != null ? Image.fromJson(json['image']) : null;
}
}
class Image {
Data? data;
Image({this.data});
Image.fromJson(Map<String, dynamic> json) {
data = json['data'] != null ? Data.fromJson(json['data']) : null;
}
}
class NestedAttributes {
String? name;
String? alternativeText;
String? caption;
int? width;
int? height;
Formats? formats;
String? hash;
String? ext;
String? mime;
double? size;
String? url;
Null? previewUrl;
String? provider;
Null? providerMetadata;
String? createdAt;
String? updatedAt;
NestedAttributes(
{this.name,
this.alternativeText,
this.caption,
this.width,
this.height,
this.formats,
this.hash,
this.ext,
this.mime,
this.size,
this.url,
this.previewUrl,
this.provider,
this.providerMetadata,
this.createdAt,
this.updatedAt});
NestedAttributes.fromJson(Map<String, dynamic> json) {
name = json['name'];
alternativeText = json['alternativeText'];
caption = json['caption'];
width = json['width'];
height = json['height'];
formats =
json['formats'] != null ? Formats.fromJson(json['formats']) : null;
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
size = json['size'];
url = json['url'];
previewUrl = json['previewUrl'];
provider = json['provider'];
providerMetadata = json['provider_metadata'];
createdAt = json['createdAt'];
updatedAt = json['updatedAt'];
}
}
class Formats {
Thumbnail? thumbnail;
Thumbnail? large;
Thumbnail? medium;
Thumbnail? small;
Formats({this.thumbnail, this.large, this.medium, this.small});
Formats.fromJson(Map<String, dynamic> json) {
thumbnail = json['thumbnail'] != null
? Thumbnail.fromJson(json['thumbnail'])
: null;
large = json['large'] != null ? Thumbnail.fromJson(json['large']) : null;
medium = json['medium'] != null ? Thumbnail.fromJson(json['medium']) : null;
small = json['small'] != null ? Thumbnail.fromJson(json['small']) : null;
}
}
class Thumbnail {
String? name;
String? hash;
String? ext;
String? mime;
int? width;
int? height;
double? size;
Null? path;
String? url;
Thumbnail(
{this.name,
this.hash,
this.ext,
this.mime,
this.width,
this.height,
this.size,
this.path,
this.url});
Thumbnail.fromJson(Map<String, dynamic> json) {
name = json['name'];
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
width = json['width'];
height = json['height'];
size = json['size'];
path = json['path'];
url = json['url'];
}
}
Try using response.data instead of response.body when you got the response.
I'm getting a Null check operator used on a null value error in flutter.
Map<String, dynamic> newUserMap = jsonDecode(authenticate.body);
print('newUserMap?');
var authNodeUser = TokenContent.fromJson(newUserMap);
print('authNodeUser?');
String? jwtToken = authNodeUser.jwtToken;
print('jwtToken = ' + authNodeUser.jwtToken!);
as I'm seeing newUserMap? and authNodeUser? I'm guessing the error occurs here;
String? jwtToken = authNodeUser.jwtToken;
print('jwtToken = ' + authNodeUser.jwtToken!);
Here's the TokenContent class;
class TokenContent {
int? currUser;
String? jwtToken;
String? refreshToken;
TokenContent({this.currUser, this.jwtToken, this.refreshToken});
TokenContent.fromJson(Map<String, dynamic> json) {
currUser = json['currUser'];
jwtToken = json['token'];
refreshToken = json['refreshToken'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['currUser'] = this.currUser;
data['jwtToken'] = this.jwtToken;
data['refreshToken'] = this.refreshToken;
return data;
}
}
How can I fix this?
Print newUserMap and make sure jwtToken exist in the http response.
I have tried to pass JSON in Post Request using BLoC Pattern.
jsonEncode(<String, String>{
'MobileNo': _emailController.value,
'Password': _passwordController.value,
'IPAddress': '192.168.0.1',
'Latitude' : '23.04503',
'Longitude': '72.55919',
"wauid" : 'd4KY17YySLC8-ROzs1RoJN:APA91bHMVz-4tw7cRIrEmBU2wHr_YW1RgV5HQfcfQp1YQwkamDPUimiPrfisezPuOgghJgHepXixsRh1Rl_eu75E9qss4RzxM6bGIgQdSo-S9TvynJsfdztz67LiaWbC9fs4xlCZnFQc'
});
I have found all the solutions to pass JSON using jsonEncode but I didn't found any solution to pass Nested JSON in Post Request of Flutter.
Here is the JSON which I am passing:
{
"userMaster": {
"MobileNo": "8800112233",
"Password": "564452",
"Latitude": 23.04503,
"Longitude": 72.55919,
"IPAddress": "5f7f51e7-09f5-4cf2-87f3-ca5760f1ed57",
"wauid": "12312"
},
"loginInfo" : {
"UserID":0
}
}
Can anyone please tell me How to send nested JSON to post the request of Flutter?
Please try below
Map<String, dynamic> payload = {
"userMaster": {
"MobileNo": "8800112233",
"Password": "564452",
"Latitude": 23.04503,
"Longitude": 72.55919,
"IPAddress": "5f7f51e7-09f5-4cf2-87f3-ca5760f1ed57",
"wauid": "12312"
},
"loginInfo" : {
"UserID":0
}
}
Response response = await http.post(<URL>,body: json.encode(payload));
It always a good practice to convert the JSON into a Model and then use it.
class UserDetails {
UserMaster userMaster;
LoginInfo loginInfo;
UserDetails({this.userMaster, this.loginInfo});
UserDetails.fromJson(Map<String, dynamic> json) {
userMaster = json['userMaster'] != null
? new UserMaster.fromJson(json['userMaster'])
: null;
loginInfo = json['loginInfo'] != null
? new LoginInfo.fromJson(json['loginInfo'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.userMaster != null) {
data['userMaster'] = this.userMaster.toJson();
}
if (this.loginInfo != null) {
data['loginInfo'] = this.loginInfo.toJson();
}
return data;
}
}
class UserMaster {
String mobileNo;
String password;
double latitude;
double longitude;
String iPAddress;
String wauid;
UserMaster(
{this.mobileNo,
this.password,
this.latitude,
this.longitude,
this.iPAddress,
this.wauid});
UserMaster.fromJson(Map<String, dynamic> json) {
mobileNo = json['MobileNo'];
password = json['Password'];
latitude = json['Latitude'];
longitude = json['Longitude'];
iPAddress = json['IPAddress'];
wauid = json['wauid'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['MobileNo'] = this.mobileNo;
data['Password'] = this.password;
data['Latitude'] = this.latitude;
data['Longitude'] = this.longitude;
data['IPAddress'] = this.iPAddress;
data['wauid'] = this.wauid;
return data;
}
}
class LoginInfo {
int userID;
LoginInfo({this.userID});
LoginInfo.fromJson(Map<String, dynamic> json) {
userID = json['UserID'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['UserID'] = this.userID;
return data;
}
}
I have converted the JSON into a Model and now you can use it where ever needed.