Flutter need help in parsing data in ListView - json

I want to know how can I convert this(for reference have a look at the screenshot attached below) JSON data into a list format in listView.builder.
Want to show latitude and longitude in the list
{
"Hyderabad" : [
{
"id": "chargeId",
"latitude" : 17.365420555196007,
"longitude" : 78.54119183209222,
"name" : "Charge And Drive Charging Station"
},
{
"id": "chargeId1",
"latitude" : 17.387480524361507,
"longitude" : 78.51581096594167,
"name" : "Electric Vehicle Charging Station"
}
],
"Banglore" : [
{
"id": "chargeId",
"latitude" : 12.978549585750843,
"longitude" : 77.59097742148764,
"name" : "Electric Vehicle Charging Station"
},
{
"id": "chargeId1",
"latitude" : 12.972527571466378,
"longitude" : 77.54737543231649,
"name" : "Charzer Charging Station Bangluru"
}
],
"Delhi" : [
{
"id": "chargeId",
"latitude" : 28.638023239349177,
"longitude" : 77.2193154296281,
"name" : "Electric Vehicle Charging Station New Delhi"
},
{
"id": "chargeId1",
"latitude" : 28.664376657655705,
"longitude" : 77.08421387364653,
"name" : "Electric Vehicle Charging Station Paschim Vihar new delhi"
}
],
"Haryana" : [
{
"id": "chargeId",
"latitude": 28.419348425880248,
"longitude": 77.31062471844143,
"name": "Tata Charging Station"
},
{
"id": "chargeId1",
"latitude": 28.396055078900797,
"longitude": 77.32257812582378,
"name": "98WF+53V, Sector 36, Sector 15, Faridabad, Haryana 121007"
}
],
"UttarPradesh" : [
{
"id": "chargeId",
"latitude" : 28.574105613931682,
"longitude" : 77.3332671026249,
"name" : "EESL Charging Station Noida"
},
{
"id":"chargeId1",
"latitude" : 28.623488529263664,
"longitude" : 77.35702730533745,
"name" : "A1 MOTORS"
}
],
"Chandigarh" : [
{
"id": "chargeId",
"latitude": 30.71576216371489,
"longitude": 76.83314092409462,
"name": "Pradeep Traders"
},
{
"id": "chargeId1",
"latitude": 30.698346233404187,
"longitude": 76.79571874441227,
"name": "Tata Power Charging Station"
}
]
}
Also here's my model class
class CoordChandigarh {
/*
{
"id": "chargeId",
"latitude": 30.71576216371489,
"longitude": 76.83314092409462,
"name": "Pradeep Traders"
}
*/
String? id;
double? latitude;
double? longitude;
String? name;
CoordChandigarh({
this.id,
this.latitude,
this.longitude,
this.name,
});
CoordChandigarh.fromJson(Map<String, dynamic> json) {
id = json["id"]?.toString();
latitude = json["latitude"]?.toDouble();
longitude = json["longitude"]?.toDouble();
name = json["name"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["id"] = id;
data["latitude"] = latitude;
data["longitude"] = longitude;
data["name"] = name;
return data;
}
}
class CoordUttarPradesh {
/*
{
"id": "chargeId",
"latitude": 28.574105613931682,
"longitude": 77.3332671026249,
"name": "EESL Charging Station Noida"
}
*/
String? id;
double? latitude;
double? longitude;
String? name;
CoordUttarPradesh({
this.id,
this.latitude,
this.longitude,
this.name,
});
CoordUttarPradesh.fromJson(Map<String, dynamic> json) {
id = json["id"]?.toString();
latitude = json["latitude"]?.toDouble();
longitude = json["longitude"]?.toDouble();
name = json["name"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["id"] = id;
data["latitude"] = latitude;
data["longitude"] = longitude;
data["name"] = name;
return data;
}
}
class CoordHaryana {
/*
{
"id": "chargeId",
"latitude": 28.419348425880248,
"longitude": 77.31062471844143,
"name": "Tata Charging Station"
}
*/
String? id;
double? latitude;
double? longitude;
String? name;
CoordHaryana({
this.id,
this.latitude,
this.longitude,
this.name,
});
CoordHaryana.fromJson(Map<String, dynamic> json) {
id = json["id"]?.toString();
latitude = json["latitude"]?.toDouble();
longitude = json["longitude"]?.toDouble();
name = json["name"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["id"] = id;
data["latitude"] = latitude;
data["longitude"] = longitude;
data["name"] = name;
return data;
}
}
class CoordDelhi {
/*
{
"id": "chargeId",
"latitude": 28.638023239349177,
"longitude": 77.2193154296281,
"name": "Electric Vehicle Charging Station New Delhi"
}
*/
String? id;
double? latitude;
double? longitude;
String? name;
CoordDelhi({
this.id,
this.latitude,
this.longitude,
this.name,
});
CoordDelhi.fromJson(Map<String, dynamic> json) {
id = json["id"]?.toString();
latitude = json["latitude"]?.toDouble();
longitude = json["longitude"]?.toDouble();
name = json["name"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["id"] = id;
data["latitude"] = latitude;
data["longitude"] = longitude;
data["name"] = name;
return data;
}
}
class CoordBanglore {
/*
{
"id": "chargeId",
"latitude": 12.978549585750843,
"longitude": 77.59097742148764,
"name": "Electric Vehicle Charging Station"
}
*/
String? id;
double? latitude;
double? longitude;
String? name;
CoordBanglore({
this.id,
this.latitude,
this.longitude,
this.name,
});
CoordBanglore.fromJson(Map<String, dynamic> json) {
id = json["id"]?.toString();
latitude = json["latitude"]?.toDouble();
longitude = json["longitude"]?.toDouble();
name = json["name"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["id"] = id;
data["latitude"] = latitude;
data["longitude"] = longitude;
data["name"] = name;
return data;
}
}
class CoordHyderabad {
/*
{
"id": "chargeId",
"latitude": 17.365420555196007,
"longitude": 78.54119183209222,
"name": "Charge And Drive Charging Station"
}
*/
String? id;
double? latitude;
double? longitude;
String? name;
CoordHyderabad({
this.id,
this.latitude,
this.longitude,
this.name,
});
CoordHyderabad.fromJson(Map<String, dynamic> json) {
id = json["id"]?.toString();
latitude = json["latitude"]?.toDouble();
longitude = json["longitude"]?.toDouble();
name = json["name"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["id"] = id;
data["latitude"] = latitude;
data["longitude"] = longitude;
data["name"] = name;
return data;
}
}
class Coord {
/*
{
"Hyderabad": [
{
"id": "chargeId",
"latitude": 17.365420555196007,
"longitude": 78.54119183209222,
"name": "Charge And Drive Charging Station"
}
],
"Banglore": [
{
"id": "chargeId",
"latitude": 12.978549585750843,
"longitude": 77.59097742148764,
"name": "Electric Vehicle Charging Station"
}
],
"Delhi": [
{
"id": "chargeId",
"latitude": 28.638023239349177,
"longitude": 77.2193154296281,
"name": "Electric Vehicle Charging Station New Delhi"
}
],
"Haryana": [
{
"id": "chargeId",
"latitude": 28.419348425880248,
"longitude": 77.31062471844143,
"name": "Tata Charging Station"
}
],
"UttarPradesh": [
{
"id": "chargeId",
"latitude": 28.574105613931682,
"longitude": 77.3332671026249,
"name": "EESL Charging Station Noida"
}
],
"Chandigarh": [
{
"id": "chargeId",
"latitude": 30.71576216371489,
"longitude": 76.83314092409462,
"name": "Pradeep Traders"
}
]
}
*/
List<CoordHyderabad?>? hyderabad;
List<CoordBanglore?>? banglore;
List<CoordDelhi?>? delhi;
List<CoordHaryana?>? haryana;
List<CoordUttarPradesh?>? uttarPradesh;
List<CoordChandigarh?>? chandigarh;
Coord({
this.hyderabad,
this.banglore,
this.delhi,
this.haryana,
this.uttarPradesh,
this.chandigarh,
});
Coord.fromJson(Map<String, dynamic> json) {
if (json["Hyderabad"] != null) {
final v = json["Hyderabad"];
final arr0 = <CoordHyderabad>[];
v.forEach((v) {
arr0.add(CoordHyderabad.fromJson(v));
});
hyderabad = arr0;
}
if (json["Banglore"] != null) {
final v = json["Banglore"];
final arr0 = <CoordBanglore>[];
v.forEach((v) {
arr0.add(CoordBanglore.fromJson(v));
});
banglore = arr0;
}
if (json["Delhi"] != null) {
final v = json["Delhi"];
final arr0 = <CoordDelhi>[];
v.forEach((v) {
arr0.add(CoordDelhi.fromJson(v));
});
delhi = arr0;
}
if (json["Haryana"] != null) {
final v = json["Haryana"];
final arr0 = <CoordHaryana>[];
v.forEach((v) {
arr0.add(CoordHaryana.fromJson(v));
});
haryana = arr0;
}
if (json["UttarPradesh"] != null) {
final v = json["UttarPradesh"];
final arr0 = <CoordUttarPradesh>[];
v.forEach((v) {
arr0.add(CoordUttarPradesh.fromJson(v));
});
uttarPradesh = arr0;
}
if (json["Chandigarh"] != null) {
final v = json["Chandigarh"];
final arr0 = <CoordChandigarh>[];
v.forEach((v) {
arr0.add(CoordChandigarh.fromJson(v));
});
chandigarh = arr0;
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
if (hyderabad != null) {
final v = hyderabad;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["Hyderabad"] = arr0;
}
if (banglore != null) {
final v = banglore;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["Banglore"] = arr0;
}
if (delhi != null) {
final v = delhi;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["Delhi"] = arr0;
}
if (haryana != null) {
final v = haryana;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["Haryana"] = arr0;
}
if (uttarPradesh != null) {
final v = uttarPradesh;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["UttarPradesh"] = arr0;
}
if (chandigarh != null) {
final v = chandigarh;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["Chandigarh"] = arr0;
}
return data;
}
}
Using Future builder to get the data but I may not know how to get a List of data from JSON file here's my Listview Data along with parsing JSON method
FutureBuilder(
future: _custJson(),
builder: (ctx, snapshot) {
// var data = coordList;
var newData = snapshot.data.toString();
print("this is delhi data ");
return ListView.builder(
itemCount: newData.length,
itemBuilder: (ctx, i) => ListTile(
title: Text(newData),
));
}),
Future<void> _custJson() async {
final String response = await rootBundle.loadString('assets/test.json');
final data = await jsonDecode(response);
final coord = Coord.fromJson(data);
return data;
print(coord);
// final coord = Coord.fromJson(data) ;
// Map<String, dynamic> userMap = jsonDecode(response);
// var user = Coord.fromJson(userMap);
// String json = jsonEncode({user});
// print(json);
}
Help me please I am badly stuck on this issue.
Appreciate your time and efforts

Related

How can i handle multiple data type for a same key from API in Flutter?

Let's explain my problem..
suppose have a json object like
from this picture i want to handle offer_price key
enter image description here
{
"product": [
{
"id": 1,
"price": 100.0,
"offer_price": 40
},
{
"id": 2,
"price": 80.0,
"offer_price": 10.50
},
{
"id": 3,
"price": 200.0,
"offer_price": "40.5"
},
{
"id": 4,
"price": 100.0,
"offer_price": null,
}
]
}
class Product {
int? id;
int? price;
// if you need the value as String
String? offerPriceAsString;
// Value as a double
double? offerPrice;
Product({this.id, this.price, this.offerPrice});
Product.fromJson(Map<String, dynamic> json) {
id = json['id'];
price = json['price'];
double.parse("1.0");
// Any value to String
offerPriceAsString = json['offer_price'].toString();
// String to Double
offerPrice = double.parse(json['offer_price'].toString());
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
data['price'] = price;
data['offer_price'] = offerPrice;
return data;
}
}
In the dart data model for offer_price field make its datatype as dynamic via which you'll be able to have a dynamic data in it as run type. And while consuming this in any place just check the runtimeType of the variable and use it by type casting or just using it with .toString().
eg class:
class Products {
Products({this.product});
Products.fromJson(Map<String, dynamic> json) {
if (json['product'] != null) {
product = <Product>[];
json['product'].forEach((v) {
product!.add(Product.fromJson(v));
});
}
}
List<Product>? product;
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (this.product != null) {
data['product'] = this.product!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Product {
Product({this.id, this.price, this.offerPrice});
Product.fromJson(Map<String, dynamic> json) {
id = json['id'];
price = json['price'];
offerPrice = json['offer_price'];
}
int? id;
int? price;
dynamic? offerPrice;
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = this.id;
data['price'] = this.price;
data['offer_price'] = this.offerPrice;
return data;
}
}
For consuming it just try:
Products products = List<Products>[];
//assign products = Products.fromJson(jsonData);
//using
products[i].offerPrice == null
? "null"
: products[i].offerPrice.runtimeType == String
? products[i].offerPrice.toString()
: products[i].offerPrice.runtimeType == Int
? int.parse(products[i].offerPrice)
: products[i].offerPrice.runtimeType == Double
? double.parse(products[i].offerPrice)
: ""

nested array list length returning all the list length

i have a complex json list in my flutter and i want to return the length of array object's nested list. but it is returning all the lists length.
my json list
{
"clients": [
{
"id": 58,
"name": "mmkmkmk",
"address": "mmakaka",
"tin_no": "9887665",
"status": "0",
"created_at": "2022-10-04T18:32:52.000000Z",
"updated_at": "2022-10-04T18:32:52.000000Z",
"phones": [
{
"id": 43,
"client_id": "58",
"supplier_id": null,
"company_id": null,
"phone_number": "987098709",
"email": "mmk#asd.fv",
"model": "Client",
"category": "Sales",
"created_at": "2022-10-04T18:32:52.000000Z",
"updated_at": "2022-10-04T18:32:52.000000Z"
}
]
},
{
"id": 59,
"name": "Konka33",
"address": "bole33",
"tin_no": "41231343",
"status": "1",
"created_at": "2022-10-04T18:33:54.000000Z",
"updated_at": "2022-10-04T18:33:54.000000Z",
"phones": [
{
"id": 44,
"client_id": "59",
"supplier_id": null,
"company_id": null,
"phone_number": "412313421",
"email": "i34#mail.com",
"model": "Client",
"category": "Manager",
"created_at": "2022-10-04T18:33:54.000000Z",
"updated_at": "2022-10-04T18:33:54.000000Z"
},
{
"id": 45,
"client_id": "59",
"supplier_id": null,
"company_id": null,
"phone_number": "-1780132721",
"email": "b34#bmail.com",
"model": "Client",
"category": "Sales",
"created_at": "2022-10-04T18:33:54.000000Z",
"updated_at": "2022-10-04T18:33:54.000000Z"
}
]
}
}
]
I want to display the selected index phones length.
I'm trying to do that by doing datasList[index].phones!.length but it's returning all of the length of the phones object from all clients phones object. not the index i wanted. how can i display the selected phones length?
client model
class Client {
List<Clients>? clients;
Client({required this.clients});
Client.fromJson(Map<String, dynamic> json) {
if (json['clients'] != null) {
clients = <Clients>[];
json['clients'].forEach((v) {
clients?.add(new Clients.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.clients != null) {
data['clients'] = this.clients!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Clients {
int? id;
String? name;
String? address;
int? tinNo;
int? status;
String? createdAt;
String? updatedAt;
List<Phones>? phones;
Clients(
{this.id,
this.name,
this.address,
this.tinNo,
this.status,
this.createdAt,
this.updatedAt,
this.phones});
Clients.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
address = json['address'];
tinNo = json['tin_no'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
if (json['phones'] != null) {
phones = <Phones>[];
json['phones'].forEach((v) {
phones!.add(new Phones.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['address'] = this.address;
data['tin_no'] = this.tinNo;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.phones != null) {
data['phones'] = this.phones!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Phones {
int? id;
int? clientId;
Null? supplierId;
Null? companyId;
int? phoneNumber;
String? email;
String? model;
String? category;
String? createdAt;
String? updatedAt;
Phones(
{this.id,
this.clientId,
this.supplierId,
this.companyId,
this.phoneNumber,
this.email,
this.model,
this.category,
this.createdAt,
this.updatedAt});
Phones.fromJson(Map<String, dynamic> json) {
id = json['id'];
clientId = json['client_id'];
supplierId = json['supplier_id'];
companyId = json['company_id'];
phoneNumber = json['phone_number'];
email = json['email'];
model = json['model'];
category = json['category'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['client_id'] = this.clientId;
data['supplier_id'] = this.supplierId;
data['company_id'] = this.companyId;
data['phone_number'] = this.phoneNumber;
data['email'] = this.email;
data['model'] = this.model;
data['category'] = this.category;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}

How to parse a complex JSON file in Flutter

I'm having a really complex JSON file to parse:
{
"adult": false,
"backdrop_url": "https://image.tmdb.org/t/p/w500/gLbBRyS7MBrmVUNce91Hmx9vzqI.jpg",
"belongs_to_collection": {
"id": 230,
"name": "The Godfather Collection",
"poster_url": "https://image.tmdb.org/t/p/w200/sSbkKCHtIEakht5rnEjrWeR2LLG.jpg",
"backdrop_url": "https://image.tmdb.org/t/p/w500/3WZTxpgscsmoUk81TuECXdFOD0R.jpg"
},
"budget": 13000000,
"genres": [
"Drama",
"Crime"
],
"homepage": null,
"id": 240,
"imdb_id": "tt0071562",
"original_language": "en",
"original_title": "The Godfather: Part II",
"overview": "In the continuing saga of the Corleone crime family, a young Vito Corleone grows up in Sicily and in 1910s New York. In the 1950s, Michael Corleone attempts to expand the family business into Las Vegas, Hollywood and Cuba.",
"popularity": 17.578,
"poster_url": "https://image.tmdb.org/t/p/w200/bVq65huQ8vHDd1a4Z37QtuyEvpA.jpg",
"production_companies": [
{
"id": 4,
"logo_url": "https://image.tmdb.org/t/p/w200/fycMZt242LVjagMByZOLUGbCvv3.png",
"name": "Paramount",
"origin_country": "US"
},
{
"id": 536,
"logo_url": null,
"name": "The Coppola Company",
"origin_country": ""
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1974-12-20",
"revenue": 102600000,
"runtime": 200,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
},
{
"iso_639_1": "it",
"name": "Italiano"
},
{
"iso_639_1": "la",
"name": "Latin"
},
{
"iso_639_1": "es",
"name": "EspaƱol"
}
],
"status": "Released",
"tagline": "I don't feel I have to wipe everybody out, Tom. Just my enemies.",
"title": "The Godfather: Part II",
"video": false,
"vote_average": 8.5,
"vote_count": 4794
}
And this is my class for parsing:
class movieDetails {
bool? adult;
String? backdropUrl;
Null? belongsToCollection;
int? budget;
List<String>? genres;
Null? homepage;
int? id;
String? imdbId;
String? originalLanguage;
String? originalTitle;
String? overview;
double? popularity;
String? posterUrl;
List<ProductionCompanies>? productionCompanies;
List<ProductionCountries>? productionCountries;
String? releaseDate;
int? revenue;
int? runtime;
List<SpokenLanguages>? spokenLanguages;
String? status;
String? tagline;
String? title;
bool? video;
double? voteAverage;
int? voteCount;
movieDetails(
{this.adult,
this.backdropUrl,
this.belongsToCollection,
this.budget,
this.genres,
this.homepage,
this.id,
this.imdbId,
this.originalLanguage,
this.originalTitle,
this.overview,
this.popularity,
this.posterUrl,
this.productionCompanies,
this.productionCountries,
this.releaseDate,
this.revenue,
this.runtime,
this.spokenLanguages,
this.status,
this.tagline,
this.title,
this.video,
this.voteAverage,
this.voteCount});
movieDetails.fromJson(Map<String, dynamic> json) {
adult = json['adult'];
backdropUrl = json['backdrop_url'];
belongsToCollection = json['belongs_to_collection'];
budget = json['budget'];
genres = json['genres'].cast<String>();
homepage = json['homepage'];
id = json['id'];
imdbId = json['imdb_id'];
originalLanguage = json['original_language'];
originalTitle = json['original_title'];
overview = json['overview'];
popularity = json['popularity'];
posterUrl = json['poster_url'];
if (json['production_companies'] != null) {
productionCompanies = <ProductionCompanies>[];
json['production_companies'].forEach((v) {
productionCompanies!.add(new ProductionCompanies.fromJson(v));
});
}
if (json['production_countries'] != null) {
productionCountries = <ProductionCountries>[];
json['production_countries'].forEach((v) {
productionCountries!.add(new ProductionCountries.fromJson(v));
});
}
releaseDate = json['release_date'];
revenue = json['revenue'];
runtime = json['runtime'];
if (json['spoken_languages'] != null) {
spokenLanguages = <SpokenLanguages>[];
json['spoken_languages'].forEach((v) {
spokenLanguages!.add(new SpokenLanguages.fromJson(v));
});
}
status = json['status'];
tagline = json['tagline'];
title = json['title'];
video = json['video'];
voteAverage = json['vote_average'];
voteCount = json['vote_count'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['adult'] = this.adult;
data['backdrop_url'] = this.backdropUrl;
data['belongs_to_collection'] = this.belongsToCollection;
data['budget'] = this.budget;
data['genres'] = this.genres;
data['homepage'] = this.homepage;
data['id'] = this.id;
data['imdb_id'] = this.imdbId;
data['original_language'] = this.originalLanguage;
data['original_title'] = this.originalTitle;
data['overview'] = this.overview;
data['popularity'] = this.popularity;
data['poster_url'] = this.posterUrl;
if (this.productionCompanies != null) {
data['production_companies'] =
this.productionCompanies!.map((v) => v.toJson()).toList();
}
if (this.productionCountries != null) {
data['production_countries'] =
this.productionCountries!.map((v) => v.toJson()).toList();
}
data['release_date'] = this.releaseDate;
data['revenue'] = this.revenue;
data['runtime'] = this.runtime;
if (this.spokenLanguages != null) {
data['spoken_languages'] =
this.spokenLanguages!.map((v) => v.toJson()).toList();
}
data['status'] = this.status;
data['tagline'] = this.tagline;
data['title'] = this.title;
data['video'] = this.video;
data['vote_average'] = this.voteAverage;
data['vote_count'] = this.voteCount;
return data;
}
}
class ProductionCompanies {
int? id;
String? logoUrl;
String? name;
String? originCountry;
ProductionCompanies({this.id, this.logoUrl, this.name, this.originCountry});
ProductionCompanies.fromJson(Map<String, dynamic> json) {
id = json['id'];
logoUrl = json['logo_url'];
name = json['name'];
originCountry = json['origin_country'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['logo_url'] = this.logoUrl;
data['name'] = this.name;
data['origin_country'] = this.originCountry;
return data;
}
}
class ProductionCountries {
String? iso31661;
String? name;
ProductionCountries({this.iso31661, this.name});
ProductionCountries.fromJson(Map<String, dynamic> json) {
iso31661 = json['iso_3166_1'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['iso_3166_1'] = this.iso31661;
data['name'] = this.name;
return data;
}
}
class SpokenLanguages {
String? iso6391;
String? name;
SpokenLanguages({this.iso6391, this.name});
SpokenLanguages.fromJson(Map<String, dynamic> json) {
iso6391 = json['iso_639_1'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['iso_639_1'] = this.iso6391;
data['name'] = this.name;
return data;
}
}
Since I'm getting this JSON from the internet, here's the fetching method:
Future<movieDetails> fetchDetails() async {
final response = await http.get(Uri.parse(url)); //url: just a string containing the website's URL
if (response.statusCode == 200){
return compute(parseDetails, response.body);
}
else{
throw Exception('Failed!');
}
}
Everything seems okay from here, but then I have literally no idea how to do the parseDetails function. How should I do it? This JSON file is too complex for me to handle.
Is there any reason you're using compute to parse the JSON file? The file you provided seems to have reasonable length and won't block the main isolate (unless the file is much bigger than what you provided, where compute might be appropriate)
Your code will be something like this (will parse the JSON response in the main isolate). For more details see the official documentation about JSON. Also a tip, follow the dart naming convention PascalCase for classes (MovieDetails instead of movieDetails)
Future<movieDetails> fetchDetails() async {
final response = await http.get(Uri.parse(url)); //url: just a string containing the website's URL
if (response.statusCode == 200){
Map<String, dynamic> movieDetailsMap = jsonDecode(response.body);
return movieDetails.fromJson(movieDetailsMap);
}
else{
throw Exception('Failed!');
}
}
movieDetails parseDetails(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return movieDetails.fromJson(parsed);
}

Parsing Nested JSON Object Flutter

I'm trying to parse an object in JSON and I am able to do so successfully without the nested JSON object Opening Hours. I don't know why. Here is the json data:
{
"location": [
{
"id": 4,
"location_name": "PastryMan",
"cbd_products": "",
"phone": "1231231234",
"street_address": "535 7th Ave",
"location_logo": "https://.s3.amazonaws.com/location_logo/water.png",
"location_photo": "https://dispensaries.s3.amazonaws.com/location_photo/delta9.jpg",
"sponsored_location": "Yes",
"city": "New York",
"state": "New York",
"zip_Code": 10018,
"lat": 40.7538935555556,
"lng": -73.9883851111111,
"latlng": "(40.7770112244898, -74.2110798163265)",
"opening_hours": [
{
"day_of_week": "Tuesday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Wednesday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Thursday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Friday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Saturday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Sunday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": 7,
"opening_time": "08:00:00",
"closing_time": "22:00:00"
}
],
"ratings": 0.0
},}
I have setup my class like this:
class Location {
int id;
String name;
String phone;
String address;
String city;
String locationPhoto;
String locationLogo;
String state;
num lat;
num long;
List<OpeningHours> openingHours;
String cbdProducts;
num rating;
String zipCode;
String latlng;
String sponsored;
location(
{this.id,
this.name,
this.cbdProducts,
this.phone,
this.address,
this.locationLogo,
this.locationPhoto,
this.sponsored,
this.city,
this.state,
this.zipCode,
this.lat,
this.long,
this.latlng,
this.openingHours,
this.rating});
location.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['location_name'];
cbdProducts = json['cbd_products'];
phone = json['phone'];
address = json['street_address'];
locationLogo = json['location_logo'];
locationPhoto = json['location_photo'];
address = json['sponsored_location'];
city = json['city'];
state = json['state'];
zipCode = json['zip_Code'];
lat = json['lat'];
long = json['long'];
latlng = json['latlng'];
if (json['opening_hours'] != null) {
openingHours = new List<OpeningHours>();
json['opening_hours'].forEach((v) {
openingHours.add(new OpeningHours.fromJson(v));
});
}
rating = json['ratings'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['location_name'] = this.name;
data['cbd_products'] = this.cbdProducts;
data['phone'] = this.phone;
data['street_address'] = this.address;
data['location_logo'] = this.locationLogo;
data['location_photo'] = this.locationPhoto;
data['sponsored_location'] = this.address;
data['city'] = this.city;
data['state'] = this.state;
data['zip_Code'] = this.zipCode;
data['lat'] = this.lat;
data['lng'] = this.long;
data['latlng'] = this.latlng;
if (this.openingHours != null) {
data['opening_hours'] = this.openingHours.map((v) => v.toJson()).toList();
}
data['ratings'] = this.rating;
return data;
}
}
class OpeningHours {
String dayOfWeek;
String openingTime;
String closingTime;
OpeningHours({this.dayOfWeek, this.openingTime, this.closingTime});
OpeningHours.fromJson(Map<String, dynamic> json) {
dayOfWeek = json['day_of_week'];
openingTime = json['opening_time'];
closingTime = json['closing_time'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['day_of_week'] = this.dayOfWeek;
data['opening_time'] = this.openingTime;
data['closing_time'] = this.closingTime;
return data;
}
}
Then I call my api in a future to get the details. Here is the api:
Future getLocations() async {
var url = '$_server/api/customer/location/';
HttpClient client = new HttpClient();
HttpClientRequest request = await client.getUrl(Uri.parse(url));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
var responseData = json.decode(reply);
Locations _location = Locations.fromJson(responseData);
currentLocations = _location.location;
print(currentLocations);
return _location.location;
}
When I call the api currentLocations = null. What have I done wrong here?
One of the easiest ways is to use quicktype.io to generate PODO (Plain Old Dart Objects). Just Select the dart language to create PODO and copy-paste your JSON over there and provide the class Name as "Location". I have done that for you now your location class will look like this:
class Location {
Location({
this.location,
});
List<LocationElement> location;
factory Location.fromJson(Map<String, dynamic> json) => Location(
location: List<LocationElement>.from(json["location"].map((x) => LocationElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"location": List<dynamic>.from(location.map((x) => x.toJson())),
};
}
class LocationElement {
LocationElement({
this.id,
this.locationName,
this.cbdProducts,
this.phone,
this.streetAddress,
this.locationLogo,
this.locationPhoto,
this.sponsoredLocation,
this.city,
this.state,
this.zipCode,
this.lat,
this.lng,
this.latlng,
this.openingHours,
this.ratings,
});
int id;
String locationName;
String cbdProducts;
String phone;
String streetAddress;
String locationLogo;
String locationPhoto;
String sponsoredLocation;
String city;
String state;
int zipCode;
double lat;
double lng;
String latlng;
List<OpeningHour> openingHours;
int ratings;
factory LocationElement.fromJson(Map<String, dynamic> json) => LocationElement(
id: json["id"],
locationName: json["location_name"],
cbdProducts: json["cbd_products"],
phone: json["phone"],
streetAddress: json["street_address"],
locationLogo: json["location_logo"],
locationPhoto: json["location_photo"],
sponsoredLocation: json["sponsored_location"],
city: json["city"],
state: json["state"],
zipCode: json["zip_Code"],
lat: json["lat"].toDouble(),
lng: json["lng"].toDouble(),
latlng: json["latlng"],
openingHours: List<OpeningHour>.from(json["opening_hours"].map((x) => OpeningHour.fromJson(x))),
ratings: json["ratings"],
);
Map<String, dynamic> toJson() => {
"id": id,
"location_name": locationName,
"cbd_products": cbdProducts,
"phone": phone,
"street_address": streetAddress,
"location_logo": locationLogo,
"location_photo": locationPhoto,
"sponsored_location": sponsoredLocation,
"city": city,
"state": state,
"zip_Code": zipCode,
"lat": lat,
"lng": lng,
"latlng": latlng,
"opening_hours": List<dynamic>.from(openingHours.map((x) => x.toJson())),
"ratings": ratings,
};
}
class OpeningHour {
OpeningHour({
this.dayOfWeek,
this.openingTime,
this.closingTime,
});
dynamic dayOfWeek;
String openingTime;
String closingTime;
factory OpeningHour.fromJson(Map<String, dynamic> json) => OpeningHour(
dayOfWeek: json["day_of_week"],
openingTime: json["opening_time"],
closingTime: json["closing_time"],
);
Map<String, dynamic> toJson() => {
"day_of_week": dayOfWeek,
"opening_time": openingTime,
"closing_time": closingTime,
};
}
This may work now and if still there is issue then you may be getting null value from backend.

How can i get all the commands id from a JSON file in flutter?

i'm a beginner in flutter and i'm trying to get values from a JSON file with flutter.
I could get some the values of the device id and devices name but i really don'y know how to get the id in commands.
Thank you in advance for your help.
Here is my JSON file :
[
{
"id": "15622bf9-969c-4f54-bd80-265a8132c97a",
"name": "Random-Integer-Generator01",
"adminState": "UNLOCKED",
"operatingState": "ENABLED",
"lastConnected": 0,
"lastReported": 0,
"labels": [
"device-random-example"
],
"location": null,
"commands": [
{
"created": 1572962679310,
"modified": 1572962679310,
"id": "f07b4a42-4358-4394-bc71-76f292f8359f",
"name": "GenerateRandomValue_Int8",
"get": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int8",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/f07b4a42-4358-4394-bc71-76f292f8359f"
},
"put": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int8",
"parameterNames": [
"Min_Int8",
"Max_Int8"
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/f07b4a42-4358-4394-bc71-76f292f8359f"
}
},
{
"created": 1572962679336,
"modified": 1572962679336,
"id": "86eafeb6-f359-40e7-b6c1-d35e9e9eb625",
"name": "GenerateRandomValue_Int16",
"get": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int16",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/86eafeb6-f359-40e7-b6c1-d35e9e9eb625"
},
"put": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int16",
"parameterNames": [
"Min_Int16",
"Max_Int16"
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/86eafeb6-f359-40e7-b6c1-d35e9e9eb625"
}
},
{
"created": 1572962679337,
"modified": 1572962679337,
"id": "bb492384-8c72-4ab6-9a84-24a3be0b934e",
"name": "GenerateRandomValue_Int32",
"get": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int32",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/bb492384-8c72-4ab6-9a84-24a3be0b934e"
},
"put": {
"path": "/api/v1/device/{deviceId}/GenerateRandomValue_Int32",
"parameterNames": [
"Min_Int32",
"Max_Int32"
],
"url": "http://edgex-core-command:48082/api/v1/device/15622bf9-969c-4f54-bd80-265a8132c97a/command/bb492384-8c72-4ab6-9a84-24a3be0b934e"
}
}
]
},
{
"id": "97dcd3b2-f4f1-4a1a-9520-2ff62c697945",
"name": "Random-Boolean-Device",
"adminState": "UNLOCKED",
"operatingState": "ENABLED",
"lastConnected": 0,
"lastReported": 0,
"labels": [
"device-virtual-example"
],
"location": null,
"commands": [
{
"created": 1572962679576,
"modified": 1572962679576,
"id": "1bc520ef-a9a4-43c7-8098-dcc5faea9ea1",
"name": "RandomValue_Bool",
"get": {
"path": "/api/v1/device/{deviceId}/RandomValue_Bool",
"responses": [
{
"code": "503",
"description": "service unavailable"
}
],
"url": "http://edgex-core-command:48082/api/v1/device/97dcd3b2-f4f1-4a1a-9520-2ff62c697945/command/1bc520ef-a9a4-43c7-8098-dcc5faea9ea1"
},
"put": {
"path": "/api/v1/device/{deviceId}/RandomValue_Bool",
"parameterNames": [
"RandomValue_Bool",
"EnableRandomization_Bool"
],
"url": "http://edgex-core-command:48082/api/v1/device/97dcd3b2-f4f1-4a1a-9520-2ff62c697945/command/1bc520ef-a9a4-43c7-8098-dcc5faea9ea1"
}
}
]
},
]
Here is my main flutter code :
import 'dart:convert';
import 'package:flutter/material.dart';
import 'GET.dart';
import 'Device.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
build(context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Http App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyListScreen(),
);
}
}
class MyListScreen extends StatefulWidget {
#override
createState() => _MyListScreenState();
}
class _MyListScreenState extends State {
var device = new List<Device>();
_getDevice() {
GET.getDevice().then((response) {
setState(() {
Iterable list = json.decode(response.body);
device = list.map((model) => Device.fromJson(model)).toList();
});
});
}
initState() {
super.initState();
_getDevice();
}
dispose() {
super.dispose();
}
#override
build(context) {
return Scaffold(
appBar: AppBar(
title: Text("Device List"),
),
body: ListView.builder(
itemCount: device.length,
itemBuilder: (context, index) {
return ListTile(title: Text("Num $index "+device[index].id));
},
));
}
}
And here is my Device class :
class Device {
//String
String id;
String name;
//String commands;
Device(String id, String name) {
this.id = id;
this.name = name;
//this.commands = commands;
//this.email = email;
}
Device.fromJson(Map json)
: id = json['id'],
name = json['name'];
// commands = json['commands'];
//['commands'][0]['name'], // marche
//email = json['email'];
Map toJson() {
return {'id': id, 'name': name};
}
}
you can cast json with below class and get commands of device with device[index].commands
class Device {
String id;
String name;
String adminState;
String operatingState;
int lastConnected;
int lastReported;
List<String> labels;
Null location;
List<Commands> commands;
Device(
{this.id,
this.name,
this.adminState,
this.operatingState,
this.lastConnected,
this.lastReported,
this.labels,
this.location,
this.commands});
Device.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
adminState = json['adminState'];
operatingState = json['operatingState'];
lastConnected = json['lastConnected'];
lastReported = json['lastReported'];
labels = json['labels'].cast<String>();
location = json['location'];
if (json['commands'] != null) {
commands = new List<Commands>();
json['commands'].forEach((v) {
commands.add(new Commands.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['adminState'] = this.adminState;
data['operatingState'] = this.operatingState;
data['lastConnected'] = this.lastConnected;
data['lastReported'] = this.lastReported;
data['labels'] = this.labels;
data['location'] = this.location;
if (this.commands != null) {
data['commands'] = this.commands.map((v) => v.toJson()).toList();
}
return data;
}
}
class Commands {
int created;
int modified;
String id;
String name;
Get get;
Put put;
Commands(
{this.created, this.modified, this.id, this.name, this.get, this.put});
Commands.fromJson(Map<String, dynamic> json) {
created = json['created'];
modified = json['modified'];
id = json['id'];
name = json['name'];
get = json['get'] != null ? new Get.fromJson(json['get']) : null;
put = json['put'] != null ? new Put.fromJson(json['put']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['created'] = this.created;
data['modified'] = this.modified;
data['id'] = this.id;
data['name'] = this.name;
if (this.get != null) {
data['get'] = this.get.toJson();
}
if (this.put != null) {
data['put'] = this.put.toJson();
}
return data;
}
}
class Get {
String path;
List<Responses> responses;
String url;
Get({this.path, this.responses, this.url});
Get.fromJson(Map<String, dynamic> json) {
path = json['path'];
if (json['responses'] != null) {
responses = new List<Responses>();
json['responses'].forEach((v) {
responses.add(new Responses.fromJson(v));
});
}
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['path'] = this.path;
if (this.responses != null) {
data['responses'] = this.responses.map((v) => v.toJson()).toList();
}
data['url'] = this.url;
return data;
}
}
class Responses {
String code;
String description;
Responses({this.code, this.description});
Responses.fromJson(Map<String, dynamic> json) {
code = json['code'];
description = json['description'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
data['description'] = this.description;
return data;
}
}
class Put {
String path;
List<String> parameterNames;
String url;
Put({this.path, this.parameterNames, this.url});
Put.fromJson(Map<String, dynamic> json) {
path = json['path'];
parameterNames = json['parameterNames'].cast<String>();
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['path'] = this.path;
data['parameterNames'] = this.parameterNames;
data['url'] = this.url;
return data;
}
}