convert json to dart - json

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);
}
}
}

Related

Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' cant fetch data

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.

How to handle different JSON Responses from same source in flutter

I have a flutter application retrieving a list/or anything for that matter at some point, and if there's any issue with the request, a different response is received.
For Example:
{
"status" : "success",
"message":
[
{
"updated_on" : "2022-01-09 14:26:07"
}
]
}
For Failure:
{
"status" : "error",
"message" : "Query not found"
}
Using quicktype.io, I have created class as below:
class ResponseList {
ResponseList({
required this.status,
required this.message,
});
String status;
List<dynamic> message;
factory ResponseList.fromJson(Map<String, dynamic> json) => ResponseList(
status: json["status"],
message: List<dynamic>.from(json["message"].map((x) => CLASSNAME.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": List<dynamic>.from(message.map((x) => x.toJson())),
};
}
Now, the problem is, on failure, this raises an exception when i try to call ResponseList responseAllFromJson(String str) => ResponseList.fromJson(json.decode(str)); where the exeption says [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'.
I want to have a method that checks the status first, whether success or failure and then parses the remaining of the json (in message) or parses the whole json and returns appropriate response (text in case of failure and list of objects in case of success).
Note: I want a reusable code, so that I can pass the response to the method and retrieve it from any point in my application. For example:
static bool responseStatus(dynamic response) {
if (response != null) {
if (responseListFromJson(response).status.trim().toLowerCase() == 'success') {
return true;
}
}
return false;
}
Presently, above raises exception on failure but works smoothly on success.
You can try this way while parsing.
class MainResponse {
String status;
dynamic message;
MainResponse({this.status, this.message});
MainResponse.fromJson(Map<String, dynamic> json) {
status = json['status'];
if(json['message'] is String) {
message = json['message'];
}else {
message = <Message>[];
json['message'].forEach((v) {
message.add(new Message.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.message != null) {
if(this.message is String) {
data['message'] = this.message;
}else {
data['message'] = this.message.map((v) => v.toJson()).toList();
}
}
return data;
}
}
class Message {
String updatedOn;
Message({this.updatedOn});
Message.fromJson(Map<String, dynamic> json) {
updatedOn = json['updated_on'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['updated_on'] = this.updatedOn;
return data;
}
}
And call this way :
MainResponse mainResponse = MainResponse.fromJson(response);
and this :
if(mainResponse.message is String) {
var data = mainResponse.message as String;
print('parsed String $data');
}else {
var list = mainResponse.message as List<Message>;
print('parsed ${list[0].updatedOn }');
}

Flutter API how can i get the data from devices in this JSON with http Plugin

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;
}
}

Dart/Flutter: Parsing Json object

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);
}
}

Parse nested JSON in Dart/Flutter

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;
}
}