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);
}
});
}
Related
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.
Could anyone advise to read the JSON in Flutter as below:
{
"1":{
"title":"ករណី ANC",
"lists":[
{
"id":"1135",
"faci_code":"20103",
"y_txt":"2022",
"m_txt":"1",
"ind_id":"1",
"qty":"67",
"rec_by":"od1234",
"rec_date":"2022-03-02 13:53:58",
"lock_txt":"0",
"sec_id":"1",
"ind_num":"1.0",
"ind_eng":"# of ANC 1",
"ind_kh":"ចំនួនស្រ្ដីបានពិនិត្យផ្ទៃពោះលើកទី១ទាំងអស់",
"HFAC_NAME":"Rung Chrey",
"HFAC_NAMEKh":"រូងជ្រៃ",
"OD_CODE":"201",
"OD_NAME":"Thma Koul",
"OD_NAME_KH":"ថ្មគោល",
"PRO_CODE":"2",
"PROVINCE":"Battambang",
"PROVINCE_KH":"បាត់ដំបង"
},
{
"id":"1136",
"faci_code":"20103",
"y_txt":"2022",
"m_txt":"1",
"ind_id":"2",
"qty":"32",
"rec_by":"od1234",
"rec_date":"2022-03-02 13:53:58",
"lock_txt":"0",
"sec_id":"1",
"ind_num":"1.1",
"ind_eng":"# of ANC 2",
"ind_kh":"ចំនួនស្រ្ដីបានពិនិត្យផ្ទៃពោះលើកទី២ទាំងអស់",
"HFAC_NAME":"Rung Chrey",
"HFAC_NAMEKh":"រូងជ្រៃ",
"OD_CODE":"201",
"OD_NAME":"Thma Koul",
"OD_NAME_KH":"ថ្មគោល",
"PRO_CODE":"2",
"PROVINCE":"Battambang",
"PROVINCE_KH":"បាត់ដំបង"
}
]
}
}
Regard, thanks.
Vandet
import dart:convert;
And then
Map<String, dynamic> dataObject = jsonDecode(yourJsonData);
See the docs: https://docs.flutter.dev/development/data-and-backend/json
From my interpretation of your question, you either want to directly access the above json in Flutter OR you want to create models out of it.
In case you want to simply use the above Json in flutter, you can simply access its values using the keys. For example: assume the above json is stored in a variable jsonString and you want to print the first list and the first element of the lists under it -
print(jsonString["1"]);
print(jsonString["1"]["lists"][0]);
In case you want to create models out of the above json, you can either do it yourself by defining encompassing objects as separate classes and going around with it OR you can use some online tool to assist you in the same, like https://javiercbk.github.io/json_to_dart/, this will create an entire converion model for you from the sample json. In case of above json it would be like -
class Autogenerated {
One? one;
Autogenerated({this.one});
Autogenerated.fromJson(Map<String, dynamic> json) {
one = json['One'] != null ? new One.fromJson(json['One']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.one != null) {
data['One'] = this.one!.toJson();
}
return data;
}
}
class One {
String? title;
List<Lists>? lists;
One({this.title, this.lists});
One.fromJson(Map<String, dynamic> json) {
title = json['title'];
if (json['lists'] != null) {
lists = <Lists>[];
json['lists'].forEach((v) {
lists!.add(new Lists.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
if (this.lists != null) {
data['lists'] = this.lists!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Lists {
String? id;
String? faciCode;
String? yTxt;
String? mTxt;
String? indId;
String? qty;
String? recBy;
String? recDate;
String? lockTxt;
String? secId;
String? indNum;
String? indEng;
String? indKh;
String? hFACNAME;
String? hFACNAMEKh;
String? oDCODE;
String? oDNAME;
String? oDNAMEKH;
String? pROCODE;
String? pROVINCE;
String? pROVINCEKH;
Lists(
{this.id,
this.faciCode,
this.yTxt,
this.mTxt,
this.indId,
this.qty,
this.recBy,
this.recDate,
this.lockTxt,
this.secId,
this.indNum,
this.indEng,
this.indKh,
this.hFACNAME,
this.hFACNAMEKh,
this.oDCODE,
this.oDNAME,
this.oDNAMEKH,
this.pROCODE,
this.pROVINCE,
this.pROVINCEKH});
Lists.fromJson(Map<String, dynamic> json) {
id = json['id'];
faciCode = json['faci_code'];
yTxt = json['y_txt'];
mTxt = json['m_txt'];
indId = json['ind_id'];
qty = json['qty'];
recBy = json['rec_by'];
recDate = json['rec_date'];
lockTxt = json['lock_txt'];
secId = json['sec_id'];
indNum = json['ind_num'];
indEng = json['ind_eng'];
indKh = json['ind_kh'];
hFACNAME = json['HFAC_NAME'];
hFACNAMEKh = json['HFAC_NAMEKh'];
oDCODE = json['OD_CODE'];
oDNAME = json['OD_NAME'];
oDNAMEKH = json['OD_NAME_KH'];
pROCODE = json['PRO_CODE'];
pROVINCE = json['PROVINCE'];
pROVINCEKH = json['PROVINCE_KH'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['faci_code'] = this.faciCode;
data['y_txt'] = this.yTxt;
data['m_txt'] = this.mTxt;
data['ind_id'] = this.indId;
data['qty'] = this.qty;
data['rec_by'] = this.recBy;
data['rec_date'] = this.recDate;
data['lock_txt'] = this.lockTxt;
data['sec_id'] = this.secId;
data['ind_num'] = this.indNum;
data['ind_eng'] = this.indEng;
data['ind_kh'] = this.indKh;
data['HFAC_NAME'] = this.hFACNAME;
data['HFAC_NAMEKh'] = this.hFACNAMEKh;
data['OD_CODE'] = this.oDCODE;
data['OD_NAME'] = this.oDNAME;
data['OD_NAME_KH'] = this.oDNAMEKH;
data['PRO_CODE'] = this.pROCODE;
data['PROVINCE'] = this.pROVINCE;
data['PROVINCE_KH'] = this.pROVINCEKH;
return data;
}
}
NOTE: Avoid using numbers as json keys.
Hello guys i want to know how can i get the data from devices in this JSON file below.
My JSON:
{
"status":"UPDATE",
"data":{
"version":"2",
"modDate":"2021-12-22T17:33:59+0100",
"languages":[
"DE",
"EN"
],
"devices":[
{
"id":126,
"uuid":"b9407f30-f5f8-466e-aff9-25556b57fe6d",
"ma":600,
"mi":33815
},
{
"id":129,
"uuid":"b9407f30-f5f8-466e-aff9-25556b57fe6d",
"ma":600,
"mi":28664
},
My Method:
Future<void> getDaten() async {
final response =
await http.get(Uri.parse("https://blablabla.de/index.php?id=7&version=2"));
final extractedData = json.decode(response.body) as Map<String, dynamic>;
print(extractedData);
extractedData.forEach((id, data) {
print(id);
print(data["devices"]);
});
}
i tried with extractedData["data"] and something else but it doesnt work.
at this actual code i get this Error
E/flutter (19705): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
Try with this, but it would good to use model class
final extractedData = json.decode(response.body) as Map<String, dynamic>;
var deviceData = extractedData["data"] as Map<String, dynamic>;
deviceData["devices"].forEach((e)=>print(e["id"])); // device id 126 129
Complete code with the model class
import 'dart:math';
void main() {
final extractedData = {
"status": "UPDATE",
"data": {
"version": "2",
"modDate": "2021-12-22T17:33:59+0100",
"languages": ["DE", "EN"],
"devices": [
{
"id": 126,
"uuid": "b9407f30-f5f8-466e-aff9-25556b57fe6d",
"ma": 600,
"mi": 33815
},
{
"id": 129,
"uuid": "b9407f30-f5f8-466e-aff9-25556b57fe6d",
"ma": 600,
"mi": 28664
},
]
}
};
ItemModel itemModel= ItemModel.fromJson(extractedData);
List<Devices>? devices = itemModel.data?.devices;
print(devices);
}
class ItemModel {
String? status;
Data? data;
ItemModel({this.status, this.data});
ItemModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.data != null) {
data['data'] = this.data!.toJson();
}
return data;
}
}
class Data {
String? version;
String? modDate;
List<String>? languages;
List<Devices>? devices;
Data({this.version, this.modDate, this.languages, this.devices});
Data.fromJson(Map<String, dynamic> json) {
version = json['version'];
modDate = json['modDate'];
languages = json['languages'].cast<String>();
if (json['devices'] != null) {
devices = <Devices>[];
json['devices'].forEach((v) {
devices!.add(new Devices.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['version'] = this.version;
data['modDate'] = this.modDate;
data['languages'] = this.languages;
if (this.devices != null) {
data['devices'] = this.devices!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Devices {
int? id;
String? uuid;
int? ma;
int? mi;
Devices({this.id, this.uuid, this.ma, this.mi});
Devices.fromJson(Map<String, dynamic> json) {
id = json['id'];
uuid = json['uuid'];
ma = json['ma'];
mi = json['mi'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['uuid'] = this.uuid;
data['ma'] = this.ma;
data['mi'] = this.mi;
return data;
}
}
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.