I am trying to decode complex json data and always resulting in error.
Below are my json data:
{
"status_code": 200,
"message": "Successfully get data user",
"data": {
"sec_user": {
"clientIp": "1.4.2.54",
"officeid": "N/A",
},
"username": "uname",
"name1": "",
"menus": [
{
"appl_id": "MTC",
"menu_caption": "Master",
"menu_path": "/master",
"submenus": [
{
"menu_caption": "Machine List",
"note1": "master",
"sub_menu_id": "1",
"route_path": "/machine_list"
},
{
"menu_caption": "Sparepart Category",
"note1": "master",
"sub_menu_id": "1",
"route_path": "/sparepart_category"
}
]
},
{
"appl_id": "MTC",
"menu_caption": "Master",
"menu_path": "/master",
"submenus": [
{
"menu_caption": "Machine List",
"note1": "master",
"sub_menu_id": "1",
"route_path": "/machine_list"
}
]
},
]
}
}
and I already create a model class using json to dart (and already retouch it a bit) and use json annotation and build runner. Then I get an error everytime I tried to decode the body of this json
if (jsonResponse.statusCode == 200) {
final jsonItems =
json.decode(jsonResponse.body).cast<Map<String, dynamic>>();
List<Profile> profile = jsonItems.map<Profile>((json) {
return MyMenu.fromJson(json);
}).toList();
return profile;
}
I always get this error message (attached on the image bellow):
What when wrong with my code ?
End up answering my question, I did this:
json.decode(jsonResponse.body)['data']['menus'].cast<Map<String, dynamic>>();
Don't know if there is any other perfect method to do this.
Your json had some syntax error as well.Please try this it if helps
import 'dart:convert';
void main() {
var jsonData= {
"status_code": 200,
"message": "Successfully get data user",
"data": {
"sec_user": {
"clientIp": "1.4.2.54",
"officeid": "N/A"
},
"username": "uname",
"name1": "",
"menus": [
{
"appl_id": "MTC",
"menu_caption": "Master",
"menu_path": "/master",
"submenus": [
{
"menu_caption": "Machine List",
"note1": "master",
"sub_menu_id": "1",
"route_path": "/machine_list"
},
{
"menu_caption": "Sparepart Category",
"note1": "master",
"sub_menu_id": "1",
"route_path": "/sparepart_category"
}
]
},
{
"appl_id": "MTC",
"menu_caption": "Master",
"menu_path": "/master",
"submenus": [
{
"menu_caption": "Machine List",
"note1": "master",
"sub_menu_id": "1",
"route_path": "/machine_list"
}
]
}
]
}
};
final jsonItems =
ApiResponse.fromJson(jsonData);
print(jsonItems.message);
}
class ApiResponse {
int statusCode;
String message;
Data data;
ApiResponse({this.statusCode, this.message, this.data});
ApiResponse.fromJson(Map<String, dynamic> json) {
statusCode = json['status_code'];
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_code'] = this.statusCode;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.toJson();
}
return data;
}
}
class Data {
SecUser secUser;
String username;
String name1;
List<Menus> menus;
Data({this.secUser, this.username, this.name1, this.menus});
Data.fromJson(Map<String, dynamic> json) {
secUser = json['sec_user'] != null
? new SecUser.fromJson(json['sec_user'])
: null;
username = json['username'];
name1 = json['name1'];
if (json['menus'] != null) {
menus = new List<Menus>();
json['menus'].forEach((v) {
menus.add(new Menus.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.secUser != null) {
data['sec_user'] = this.secUser.toJson();
}
data['username'] = this.username;
data['name1'] = this.name1;
if (this.menus != null) {
data['menus'] = this.menus.map((v) => v.toJson()).toList();
}
return data;
}
}
class SecUser {
String clientIp;
String officeid;
SecUser({this.clientIp, this.officeid});
SecUser.fromJson(Map<String, dynamic> json) {
clientIp = json['clientIp'];
officeid = json['officeid'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['clientIp'] = this.clientIp;
data['officeid'] = this.officeid;
return data;
}
}
class Menus {
String applId;
String menuCaption;
String menuPath;
List<Submenus> submenus;
Menus({this.applId, this.menuCaption, this.menuPath, this.submenus});
Menus.fromJson(Map<String, dynamic> json) {
applId = json['appl_id'];
menuCaption = json['menu_caption'];
menuPath = json['menu_path'];
if (json['submenus'] != null) {
submenus = new List<Submenus>();
json['submenus'].forEach((v) {
submenus.add(new Submenus.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['appl_id'] = this.applId;
data['menu_caption'] = this.menuCaption;
data['menu_path'] = this.menuPath;
if (this.submenus != null) {
data['submenus'] = this.submenus.map((v) => v.toJson()).toList();
}
return data;
}
}
class Submenus {
String menuCaption;
String note1;
String subMenuId;
String routePath;
Submenus({this.menuCaption, this.note1, this.subMenuId, this.routePath});
Submenus.fromJson(Map<String, dynamic> json) {
menuCaption = json['menu_caption'];
note1 = json['note1'];
subMenuId = json['sub_menu_id'];
routePath = json['route_path'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['menu_caption'] = this.menuCaption;
data['note1'] = this.note1;
data['sub_menu_id'] = this.subMenuId;
data['route_path'] = this.routePath;
return data;
}
}
Related
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);
}
I want to parse this Json. Now i am parsing Load as a class with 2 fields: id, and value. But what i want to is to parse it like Map<int, String>. When i am trying to cast the object, flutter gives me an error. for example:
Map<int, String> map = {
38 : "#1038 Fort Dodge, IA - Algona, IA",
39 : "#1039 Louisville, KY - Louisville, KY"
}
it is not the same as this question
{
"loads": {
"data": [
{
"id": 38,
"value": "#1038 Fort Dodge, IA - Algona, IA"
},
{
"id": 39,
"value": "#1039 Louisville, KY - Louisville, KY"
}
]
},
"date_ranges": {
"data": [
{
"id": "all_time",
"value": "All"
},
{
"id": "this_year",
"value": "This year"
}
]
}
}
You can create pojo class to parse your JSON
TestModel testModel = TestModel.fromJson(yourResponse);
class TestModel {
Loads loads;
Loads dateRanges;
TestModel({this.loads, this.dateRanges});
TestModel.fromJson(Map<String, dynamic> json) {
loads = json['loads'] != null ? new Loads.fromJson(json['loads']) : null;
dateRanges = json['date_ranges'] != null
? new Loads.fromJson(json['date_ranges'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.loads != null) {
data['loads'] = this.loads.toJson();
}
if (this.dateRanges != null) {
data['date_ranges'] = this.dateRanges.toJson();
}
return data;
}
}
class Loads {
List<Data> data;
Loads({this.data});
Loads.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 {
int id;
String value;
Data({this.id, this.value});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['value'] = this.value;
return data;
}
}
class Data {
String id;
String value;
Data({this.id, this.value});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['value'] = this.value;
return data;
}
}
There was a issue you found because loads and date_ranges contain same child name data but there properties are different that's why your model class return error
Here I write a code for loads, please have a look
void main() {
Map<int, String> map = {
};
var mapdata = {
"loads": {
"data": [
{
"id": 50,
"value": "#1038 Fort Dodge, IA - Algona, IA"
},
{
"id": 39,
"value": "#1039 Louisville, KY - Louisville, KY"
}
]
},
"date_ranges": {
"data": [
{
"id": "all_time",
"value": "All"
},
{
"id": "this_year",
"value": "This year"
}
]
}
};
TestModel test = TestModel.fromJson(mapdata);
test.loads.data.forEach((e)=>map[e.id]=e.value);
print(map);
}
class TestModel {
Loads loads;
Loads dateRanges;
TestModel({this.loads, this.dateRanges});
TestModel.fromJson(Map<String, dynamic> json) {
loads = json['loads'] != null ? new Loads.fromJson(json['loads']) : null;
dateRanges = json['date_ranges'] != null
? new Loads.fromJson(json['date_ranges'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.loads != null) {
data['loads'] = this.loads.toJson();
}
if (this.dateRanges != null) {
data['date_ranges'] = this.dateRanges.toJson();
}
return data;
}
}
class Loads {
List<Data> data;
Loads({this.data});
Loads.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 {
var id; // here changes the type
String value;
Data({this.id, this.value});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
value = json['value'];
}
Map<String, String> toJson() {
final Map<String, String> data = new Map<String, String>();
data['id'] = this.id;
data['value'] = this.value;
return data;
}
}
map result:
{50: #1038 Fort Dodge, IA - Algona, IA, 39: #1039 Louisville, KY - Louisville, KY}
N.B: Make your id dynamic with var type
i have a problem with a json response
Json it's:
{
"SData": {
"total": "1",
"STable": {
"year": "2020",
"S1Lists": [
{
"year": "2020",
"turn": "6",
"Ranking": [
{
"position": "1",
"Person": {
"personId": "paul",
"nationality": "none"
},
},
]
}
]
}
}
Dart code
if(response.statusCode == 200){
final result = response.data;
Iterable list = result['SData'];
print(list);
}else{
throw Exception("Fail!");
}
and i receive this error
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'
how can i solve if, for example, i want to access the position field or the personId field
This happens because your json output is a Map<String, dynamic> and not a Iterable.
if (response.statusCode == 200) {
final result = response.data;
final Map<String, dynamic> map = result['SData'];
print(map );
} else {
throw Exception("Fail!");
}
Which will print this output
{
"total":1,
"STable":{
"year":2020,
"S1Lists":[
{
"year":2020,
"turn":6,
"Ranking":[
{
"position":1,
"Person":{
"personId":"paul",
"nationality":"none"
}
}
]
}
]
}
}
If you want to get the ranking.
final Map<String, dynamic> data = result ['SData'];
final Map<String, dynamic> table = data['STable']; // This is like result['SData']['STable']
final Map<String, dynamic> list = table['S1Lists']; // result['SData']['STable']['S1Lists']
final Map<String, dynamic> firstItem = list[0]; // result['SData']['STable']['S1Lists'][0]
final Map<String, dynamic> ranking = list['Ranking']; // result['SData']['STable']['S1Lists'][0]['Ranking']
Below is my json response, i want to get this response into model and nested model class. Please help me to read this json. Thanks in advance. I am new in flutter to parse json response in model class.
'''
{
"success": 1,
"totalResults": 5,
"data": [
{
"id": 1,
"bank_name": "SBI bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/1/sbi-round-logo.png",
"bank_desc": "sbi",
"rating": "AA"
},
{
"id": 2,
"bank_name": "Yes bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/2/yes-round-logo.png",
"bank_desc": "Yes bank",
"rating": "AA"
},
{
"id": 3,
"bank_name": "Union bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/3/union-round-logo.png",
"bank_desc": "union bank",
"rating": "AA"
},
{
"id": 9,
"bank_name": "Bank of Baroda",
"bank_logo": "http://3.143.33.201/assets/banklogo/9/bob.png",
"bank_desc": "Bank of Baroda",
"rating": "AA"
},
{
"id": 10,
"bank_name": "IndusInd Bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/10/Indus-bank-2.png",
"bank_desc": "IndusInd Bank",
"rating": "AA"
}
]
}
'''
We have a inbuilt package in dart for it,
dart:convert, the usage is as follows
import 'dart:convert' as convert;
...
// perform your http request and get the response from it,
var responseData = convert.jsonDecode(response.body);
convert.jsonDecode() will enable accessing the data stores in the responseData with key values.
#note : I have imported it as convert as for my convenience as I don't get confused while development.
Happy coding
You can use JSON and serialization for this
final _response = jsonDecode(jsonResponse);
After that you can use _response data in your model class like this
YourModel.fromJson(_response);
Initialize your model and use like this
final YourModel _yourModel = YourModel();
final _isSuccess = _yourModel.success;
final _data = _yourModel.data;
Step 1 >
Creat BankDataModel.dart
class BankDataModel {
int? success;
int? totalResults;
List<Data>? data;
BankDataModel({this.success, this.totalResults, this.data});
BankDataModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
totalResults = json['totalResults'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['totalResults'] = this.totalResults;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
int? id;
String? bankName;
String? bankLogo;
String? bankDesc;
String? rating;
Data({this.id, this.bankName, this.bankLogo, this.bankDesc, this.rating});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
bankName = json['bank_name'];
bankLogo = json['bank_logo'];
bankDesc = json['bank_desc'];
rating = json['rating'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['bank_name'] = this.bankName;
data['bank_logo'] = this.bankLogo;
data['bank_desc'] = this.bankDesc;
data['rating'] = this.rating;
return data;
}
}
Step 2>
Crete Object you want use
BankDataModel _bankDataModel = BankDataModel();
Step 3>
Api call
Future<BankDataModel> getData() async {
BankDataModel _bankDataModel = BankDataModel();
final url = 'your-url';
try {
final response = await client.get(url);
if (response.statusCode == 200) {
_bankDataModel = BankDataModel.fromJson(response.data); < -- Here Json to BankDataModel Convert..
print(_bankDataModel.totalResults.toString()); < -- here print 5 as per question.
return _bankDataModel;
} else {
print(response.statusCode);
throw response.statusCode;
}
} catch (error) {
print(error);
}
}
Thanks you. Happy to help you.
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;
}
}