I am trying to parse some unique JSON data in my Flutter app.
{
"NewDataSet": {
"Route": [
{
"RouteID": "1",
"RouteNum": "20",
"Description": "NORTH DAKOTA "
},
{
"RouteID": "11",
"RouteNum": "25",
"Description": "East SD "
}
]
}
}
I am not sure how to parse this with two objects.
You can use json2dart to convert your json to dart classes even complex and nested json datas will work perfectly.
Here is dart class version of your given json data:
class Autogenerated {
NewDataSet newDataSet;
Autogenerated({this.newDataSet});
Autogenerated.fromJson(Map<String, dynamic> json) {
newDataSet = json['NewDataSet'] != null
? new NewDataSet.fromJson(json['NewDataSet'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.newDataSet != null) {
data['NewDataSet'] = this.newDataSet.toJson();
}
return data;
}
}
class NewDataSet {
List<Route> route;
NewDataSet({this.route});
NewDataSet.fromJson(Map<String, dynamic> json) {
if (json['Route'] != null) {
route = new List<Route>();
json['Route'].forEach((v) {
route.add(new Route.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.route != null) {
data['Route'] = this.route.map((v) => v.toJson()).toList();
}
return data;
}
}
class Route {
String routeID;
String routeNum;
String description;
Route({this.routeID, this.routeNum, this.description});
Route.fromJson(Map<String, dynamic> json) {
routeID = json['RouteID'];
routeNum = json['RouteNum'];
description = json['Description'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['RouteID'] = this.routeID;
data['RouteNum'] = this.routeNum;
data['Description'] = this.description;
return data;
}
}
You can chain the square brackets and simply refer to the respective names, as long as you know the data you're receiving.
import 'dart:convert';
void main() {
decodeJSON();
}
void decodeJSON() async {
String data =
'{"NewDataSet": {"Route": [{"RouteID": "1","RouteNum": "20","Description": "NORTH DAKOTA "},{"RouteID": "11","RouteNum": "25","Description": "East SD "}]}}';
try {
dynamic decoded = await jsonDecode(data);
dynamic newDataSet = await decoded['NewDataSet'];
dynamic routes = await decoded['NewDataSet']['Route'];
print(newDataSet);
print(routes);
} catch (e) {
print(e);
}
}
Related
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 am a beginner in Flutter, I just want to know how to print productA and 220 in console. The below is json file and also create dart file below.
{
"status": true,
"message": "Data returned successfull",
"data": {
"products": [
{
"productName": "productA",
"productPrice": "220.00",
}
]
}
}
Product.dart
class Product {
bool status;
String message;
Data data;
Product({this.status, this.message, this.data});
Product.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
}
class Data {
List<Products> products;
Data({this.products});
Data.fromJson(Map<String, dynamic> json) {
if (json['products'] != null) {
products = new List<Products>();
json['products'].forEach((v) {
products.add(new Products.fromJson(v));
});
}
}
}
class Products {
String prodName;
String prodRkPrice;
Products({this.prodName, this.prodRkPrice});
Products.fromJson(Map<String, dynamic> json) {
prodName = json['prodName'];
prodRkPrice = json['prodRkPrice'];
}
}
But still don't know how to print those values.
fetchData() async {
try {
String extractedData =
await http.get('json url').toString();
final parsed = jsonDecode(extractedData).cast(Map<String, dynamic>());
final products = Product.fromJson(parsed);
print(products);
//print(json.decode(response.body));
//print(response[0]);
} catch (error) {
throw (error);
}
}
I have tried using this method but getting errors, don't know how to parse and print those values?
Please help me I am a beginner in Flutter
Change your fetchData to:
Future<void> fetchData() async {
try {
Response response = await http.get('json url'); //getting the response without .toString
Map<String, dynamic> extractedData = jsonDecode(response.body); //converting the response
Product products = Product.fromJson(extractedData);
products.data.products.forEach((product) {
print(product.prodName);
print(product.prodRkPrice);
});
} catch (error) {
throw (error);
}
}
Just remember to match the same attribute names of the api in the Products class:
Products.fromJson(Map<String, dynamic> json) {
prodName = json['productName'];
prodRkPrice = json['productPrice'];
}
This should work:
Map<String, dynamic> message = jsonDecode('{"status": true,"message": "Data returned successfull","data": {"products": [{"productName": "productA","productPrice": "220.00"}]}}');
print(message["data"]["products"][0]["productName"]);
What errors are you getting?
Please try this function
fetchData() async {
try {
var extractedData = await http.get('json url');
Product finalResponse = Product.fromJson(jsonDecode(extractedData.body));
print(finalResponse.products[0].productName);
print(finalResponse);
} catch (error) {
throw (error);
}
}
String urlBase = "https://.....";
Future fetchData async {
var jsonResponse;
var response = await http.get("$urlBase");
if (response != null && response.statusCode == 200) {
jsonResponse = json.decode(response.body);
Object obj= jsonDecode(response.body);
return obj;
} else {
//do something else
}
}
To access the Product A and 220, first you should convert json response into dart object. I Try free online JSON to Dart convertor and here is dart object class
class product_model {
bool status;
String message;
Data data;
product_model({this.status, this.message, this.data});
product_model.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
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;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.toJson();
}
return data;
}
}
class Data {
List<Products> products;
Data({this.products});
Data.fromJson(Map<String, dynamic> json) {
if (json['products'] != null) {
products = new List<Products>();
json['products'].forEach((v) {
products.add(new Products.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.products != null) {
data['products'] = this.products.map((v) => v.toJson()).toList();
}
return data;
}
}
class Products {
String productName;
String productPrice;
Products({this.productName, this.productPrice});
Products.fromJson(Map<String, dynamic> json) {
productName = json['productName'];
productPrice = json['productPrice'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['productName'] = this.productName;
data['productPrice'] = this.productPrice;
return data;
}
}
To access the Product A and value 220, Please use below code.
final Map<String, dynamic> parsed = await wrapper.get_CategoryFull(catid);
final model = product_model.fromJson(parsed);
if (model.data.length > 0) {
if (model.products.length > 0) {
for (int i = 0; i < model.products.length; i++) {
print(" product name " +model.products[i].productName);
print(" product price " +model.products[i].productPrice);
}
}
}
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.
I dont know how to fix this error.
Exception has occurred.
_TypeError (type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f')
class _ShowformState extends State<Showform> {
List<MaintenanceInfo> info = [];
#override
void initState() {
super.initState();
fetchData();
}
void fetchData() async {
final data = await http.get('http://192.168.1.35:7000/');
print(data.body);
final jsonData = json.decode(data.body);
setState(() {
jsonData.forEach((v) {
var tmpData = MaintenanceInfo.fromJson(v);
info.add(tmpData);
});
});
}
MaintenanceInfo maintenanceInfoFromJson(String str) =>
MaintenanceInfo.fromJson(json.decode(str));
String maintenanceInfoToJson(MaintenanceInfo data) =>
json.encode(data.toJson());
class MaintenanceInfo {
MaintenanceInfo(
{this.serial,
this.model,
});
String serial;
String model;
factory MaintenanceInfo.fromJson(Map<String, dynamic> json) =>
MaintenanceInfo(
serial: json['serial'],
model: json['model'],);
Map<String, dynamic> toJson() => {
'serial': serial,
'model': model, };}
JSON Format look like this
{ "data": [
{
"serial": "8850124003850",
"model": "280",
},]
}
Ps. I am new on flutter development.
Your model looks problematic. You need to modify it like this:
class MaintenanceInfo {
List<Data> data;
MaintenanceInfo({this.data});
MaintenanceInfo.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String serial;
String model;
Data({this.serial, this.model});
Data.fromJson(Map<String, dynamic> json) {
serial = json['serial'];
model = json['model'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['serial'] = this.serial;
data['model'] = this.model;
return data;
}
}
You can use this website to convert the JSON to Dart Model.
I'm trying to parse my JSON into Data class object. I did some research and did come upon some helpful articles but am still running into errors.
The response I get from the backend:
"entrances": {
"options": {
"mainEntrance": {
"text": "Enter through the main doors"
},
"backEntrance": {
"text": "Enter through the back doors"
},
"sideEntrance": {
"text": "Enter through the side doors"
}
},
"footer": "Text goes here"
},
"status": {
"state": "open"
}
}
Model
class MyClass {
String id;
Options option;
MyClass({this.id, this.option});
MyClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
option = json['option'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['option'] = this.option;
return data;
}
}
class Options {
String name;
String text;
Options({this.name, this.text});
Options.fromJson(Map<String, dynamic> json) {
name = json['name'];
text = json['text'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['text'] = this.text;
return data;
}
}
Decoding the response and mapping
setState(() {
Map myMap = json.decode(response.body);
List<MyClass> myClassList = new List<MyClass>();
myMap['entrances'].forEach((key, value) {
value['id'] = key;
myClassList.add(MyClass.fromJson(value));
});
myClassList.forEach((MyClass) {
print(MyClass.id);
print(MyClass.option.name);
print("--------------------\n");
});
});
I get this error:
Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method '[]='.
Tried calling: []=("id", "footer")
What am I doing wrong? Are there better approaches out there?
You can use this website to convert your JSON to a Dart model. I assume that your JSON starts with curly brackets.
{
"entrances": {
"options": {
"mainEntrance": {
"text": "Enter through the main doors"
},
"backEntrance": {
"text": "Enter through the back doors"
},
"sideEntrance": {
"text": "Enter through the side doors"
}
},
"footer": "Text goes here"
},
"status": {
"state": "open"
}
}
Then your model should look like:
class ResponseModel {
Entrances entrances;
Status status;
ResponseModel({this.entrances, this.status});
ResponseModel.fromJson(Map<String, dynamic> json) {
entrances = json['entrances'] != null
? new Entrances.fromJson(json['entrances'])
: null;
status =
json['status'] != null ? new Status.fromJson(json['status']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.entrances != null) {
data['entrances'] = this.entrances.toJson();
}
if (this.status != null) {
data['status'] = this.status.toJson();
}
return data;
}
}
class Entrances {
Options options;
String footer;
Entrances({this.options, this.footer});
Entrances.fromJson(Map<String, dynamic> json) {
options =
json['options'] != null ? new Options.fromJson(json['options']) : null;
footer = json['footer'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.options != null) {
data['options'] = this.options.toJson();
}
data['footer'] = this.footer;
return data;
}
}
class Options {
MainEntrance mainEntrance;
MainEntrance backEntrance;
MainEntrance sideEntrance;
Options({this.mainEntrance, this.backEntrance, this.sideEntrance});
Options.fromJson(Map<String, dynamic> json) {
mainEntrance = json['mainEntrance'] != null
? new MainEntrance.fromJson(json['mainEntrance'])
: null;
backEntrance = json['backEntrance'] != null
? new MainEntrance.fromJson(json['backEntrance'])
: null;
sideEntrance = json['sideEntrance'] != null
? new MainEntrance.fromJson(json['sideEntrance'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.mainEntrance != null) {
data['mainEntrance'] = this.mainEntrance.toJson();
}
if (this.backEntrance != null) {
data['backEntrance'] = this.backEntrance.toJson();
}
if (this.sideEntrance != null) {
data['sideEntrance'] = this.sideEntrance.toJson();
}
return data;
}
}
class MainEntrance {
String text;
MainEntrance({this.text});
MainEntrance.fromJson(Map<String, dynamic> json) {
text = json['text'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['text'] = this.text;
return data;
}
}
class Status {
String state;
Status({this.state});
Status.fromJson(Map<String, dynamic> json) {
state = json['state'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['state'] = this.state;
return data;
}
}