I used a converter but the result was wrong...
Am trying to develop application about Covid-19 using flutter and am kinda stuck on this format of result.I need to converted to dart to keep working on the app so any help will be appreciate and thanks in advance :)
This is the result of the request from the api:
[
{
"country": "Afghanistan",
"province": null,
"timeline": {
"cases": {
"3/16/20": 21,
"3/17/20": 22,
"3/18/20": 22,
"3/19/20": 22,
"3/20/20": 24,
"3/21/20": 24,
"3/22/20": 40,
"3/23/20": 40,
"3/24/20": 74,
"3/25/20": 84,
"3/26/20": 94,
"3/27/20": 110,
"3/28/20": 110,
"3/29/20": 120,
"3/30/20": 170,
"3/31/20": 174,
"4/1/20": 237,
"4/2/20": 273,
"4/3/20": 281,
"4/4/20": 299,
"4/5/20": 349,
"4/6/20": 367,
"4/7/20": 423,
"4/8/20": 444,
"4/9/20": 484,
"4/10/20": 521,
"4/11/20": 555,
"4/12/20": 607,
"4/13/20": 665,
"4/14/20": 714
},
"deaths": {
"3/16/20": 0,
"3/17/20": 0,
"3/18/20": 0,
"3/19/20": 0,
"3/20/20": 0,
"3/21/20": 0,
"3/22/20": 1,
"3/23/20": 1,
"3/24/20": 1,
"3/25/20": 2,
"3/26/20": 4,
"3/27/20": 4,
"3/28/20": 4,
"3/29/20": 4,
"3/30/20": 4,
"3/31/20": 4,
"4/1/20": 4,
"4/2/20": 6,
"4/3/20": 6,
"4/4/20": 7,
"4/5/20": 7,
"4/6/20": 11,
"4/7/20": 14,
"4/8/20": 14,
"4/9/20": 15,
"4/10/20": 15,
"4/11/20": 18,
"4/12/20": 18,
"4/13/20": 21,
"4/14/20": 23
},
"recovered": {
"3/16/20": 1,
"3/17/20": 1,
"3/18/20": 1,
"3/19/20": 1,
"3/20/20": 1,
"3/21/20": 1,
"3/22/20": 1,
"3/23/20": 1,
"3/24/20": 1,
"3/25/20": 2,
"3/26/20": 2,
"3/27/20": 2,
"3/28/20": 2,
"3/29/20": 2,
"3/30/20": 2,
"3/31/20": 5,
"4/1/20": 5,
"4/2/20": 10,
"4/3/20": 10,
"4/4/20": 10,
"4/5/20": 15,
"4/6/20": 18,
"4/7/20": 18,
"4/8/20": 29,
"4/9/20": 32,
"4/10/20": 32,
"4/11/20": 32,
"4/12/20": 32,
"4/13/20": 32,
"4/14/20": 40
}
}
},
...
]
And this the result from converter:
class Historic {
String country;
Null province;
Timeline timeline;
Historic({this.country, this.province, this.timeline});
Historic.fromJson(Map<String, dynamic> json) {
country = json['country'];
province = json['province'];
timeline = json['timeline'] != null
? new Timeline.fromJson(json['timeline'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['country'] = this.country;
data['province'] = this.province;
if (this.timeline != null) {
data['timeline'] = this.timeline.toJson();
}
return data;
}
}
class Timeline {
Cases cases;
Cases deaths;
Cases recovered;
Timeline({this.cases, this.deaths, this.recovered});
Timeline.fromJson(Map<String, dynamic> json) {
cases = json['cases'] != null ? new Cases.fromJson(json['cases']) : null;
deaths = json['deaths'] != null ? new Cases.fromJson(json['deaths']) : null;
recovered = json['recovered'] != null
? new Cases.fromJson(json['recovered'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.cases != null) {
data['cases'] = this.cases.toJson();
}
if (this.deaths != null) {
data['deaths'] = this.deaths.toJson();
}
if (this.recovered != null) {
data['recovered'] = this.recovered.toJson();
}
return data;
}
}
class Cases {
int i31620;
int i31720;
int i31820;
int i31920;
int i32020;
int i32120;
int i32220;
int i32320;
int i32420;
int i32520;
int i32620;
int i32720;
int i32820;
int i32920;
int i33020;
int i33120;
int i4120;
int i4220;
int i4320;
int i4420;
int i4520;
int i4620;
int i4720;
int i4820;
int i4920;
int i41020;
int i41120;
int i41220;
int i41320;
int i41420;
Cases(
{this.i31620,
this.i31720,
this.i31820,
this.i31920,
this.i32020,
this.i32120,
this.i32220,
this.i32320,
this.i32420,
this.i32520,
this.i32620,
this.i32720,
this.i32820,
this.i32920,
this.i33020,
this.i33120,
this.i4120,
this.i4220,
this.i4320,
this.i4420,
this.i4520,
this.i4620,
this.i4720,
this.i4820,
this.i4920,
this.i41020,
this.i41120,
this.i41220,
this.i41320,
this.i41420});
Cases.fromJson(Map<String, dynamic> json) {
i31620 = json['3/16/20'];
i31720 = json['3/17/20'];
i31820 = json['3/18/20'];
i31920 = json['3/19/20'];
i32020 = json['3/20/20'];
i32120 = json['3/21/20'];
i32220 = json['3/22/20'];
i32320 = json['3/23/20'];
i32420 = json['3/24/20'];
i32520 = json['3/25/20'];
i32620 = json['3/26/20'];
i32720 = json['3/27/20'];
i32820 = json['3/28/20'];
i32920 = json['3/29/20'];
i33020 = json['3/30/20'];
i33120 = json['3/31/20'];
i4120 = json['4/1/20'];
i4220 = json['4/2/20'];
i4320 = json['4/3/20'];
i4420 = json['4/4/20'];
i4520 = json['4/5/20'];
i4620 = json['4/6/20'];
i4720 = json['4/7/20'];
i4820 = json['4/8/20'];
i4920 = json['4/9/20'];
i41020 = json['4/10/20'];
i41120 = json['4/11/20'];
i41220 = json['4/12/20'];
i41320 = json['4/13/20'];
i41420 = json['4/14/20'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['3/16/20'] = this.i31620;
data['3/17/20'] = this.i31720;
data['3/18/20'] = this.i31820;
data['3/19/20'] = this.i31920;
data['3/20/20'] = this.i32020;
data['3/21/20'] = this.i32120;
data['3/22/20'] = this.i32220;
data['3/23/20'] = this.i32320;
data['3/24/20'] = this.i32420;
data['3/25/20'] = this.i32520;
data['3/26/20'] = this.i32620;
data['3/27/20'] = this.i32720;
data['3/28/20'] = this.i32820;
data['3/29/20'] = this.i32920;
data['3/30/20'] = this.i33020;
data['3/31/20'] = this.i33120;
data['4/1/20'] = this.i4120;
data['4/2/20'] = this.i4220;
data['4/3/20'] = this.i4320;
data['4/4/20'] = this.i4420;
data['4/5/20'] = this.i4520;
data['4/6/20'] = this.i4620;
data['4/7/20'] = this.i4720;
data['4/8/20'] = this.i4820;
data['4/9/20'] = this.i4920;
data['4/10/20'] = this.i41020;
data['4/11/20'] = this.i41120;
data['4/12/20'] = this.i41220;
data['4/13/20'] = this.i41320;
data['4/14/20'] = this.i41420;
return data;
}
}
You could use this simple function to turn the date strings to DateTime object.
DateTime parseDate(String raw){
int year = int.parse(raw[2]);
int month = int.parse(raw[0]);
int day = int.parse(raw[1]);
return DateTime(year, month, day);
}
Update i found solution:
import 'dart:convert';
List<Historic> historicFromJson(String str) =>
List<Historic>.from(json.decode(str).map((x) => Historic.fromJson(x)));
String historicToJson(List<Historic> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Historic {
String country;
String province;
Timeline timeline;
Historic({
this.country,
this.province,
this.timeline,
});
factory Historic.fromJson(Map<String, dynamic> json) => Historic(
country: json["country"],
province: json["province"] == null ? null : json["province"],
timeline: Timeline.fromJson(json["timeline"]),
);
Map<String, dynamic> toJson() => {
"country": country,
"province": province == null ? null : province,
"timeline": timeline.toJson(),
};
}
class Timeline {
Map<String, int> cases;
Map<String, int> deaths;
Map<String, int> recovered;
Timeline({
this.cases,
this.deaths,
this.recovered,
});
factory Timeline.fromJson(Map<String, dynamic> json) => Timeline(
cases:
Map.from(json["cases"]).map((k, v) => MapEntry<String, int>(k, v)),
deaths:
Map.from(json["deaths"]).map((k, v) => MapEntry<String, int>(k, v)),
recovered: Map.from(json["recovered"])
.map((k, v) => MapEntry<String, int>(k, v)),
);
Map<String, dynamic> toJson() => {
"cases": Map.from(cases).map((k, v) => MapEntry<String, dynamic>(k, v)),
"deaths":
Map.from(deaths).map((k, v) => MapEntry<String, dynamic>(k, v)),
"recovered":
Map.from(recovered).map((k, v) => MapEntry<String, dynamic>(k, v)),
};
}
An even faster way is to use this web tool for instant conversion from JSON. You just need to paste the JSON code in (remember to respect the format), choose the language output and voila!
Input (Copy this):
{
"country": "Afghanistan",
"province": null,
"timeline": {
"cases": {
"3/16/20": 21,
"3/17/20": 22,
"3/18/20": 22,
"3/19/20": 22,
"3/20/20": 24,
"3/21/20": 24,
"3/22/20": 40,
"3/23/20": 40,
"3/24/20": 74,
"3/25/20": 84,
"3/26/20": 94,
"3/27/20": 110,
"3/28/20": 110,
"3/29/20": 120,
"3/30/20": 170,
"3/31/20": 174,
"4/1/20": 237,
"4/2/20": 273,
"4/3/20": 281,
"4/4/20": 299,
"4/5/20": 349,
"4/6/20": 367,
"4/7/20": 423,
"4/8/20": 444,
"4/9/20": 484,
"4/10/20": 521,
"4/11/20": 555,
"4/12/20": 607,
"4/13/20": 665,
"4/14/20": 714
},
"deaths": {
"3/16/20": 0,
"3/17/20": 0,
"3/18/20": 0,
"3/19/20": 0,
"3/20/20": 0,
"3/21/20": 0,
"3/22/20": 1,
"3/23/20": 1,
"3/24/20": 1,
"3/25/20": 2,
"3/26/20": 4,
"3/27/20": 4,
"3/28/20": 4,
"3/29/20": 4,
"3/30/20": 4,
"3/31/20": 4,
"4/1/20": 4,
"4/2/20": 6,
"4/3/20": 6,
"4/4/20": 7,
"4/5/20": 7,
"4/6/20": 11,
"4/7/20": 14,
"4/8/20": 14,
"4/9/20": 15,
"4/10/20": 15,
"4/11/20": 18,
"4/12/20": 18,
"4/13/20": 21,
"4/14/20": 23
},
"recovered": {
"3/16/20": 1,
"3/17/20": 1,
"3/18/20": 1,
"3/19/20": 1,
"3/20/20": 1,
"3/21/20": 1,
"3/22/20": 1,
"3/23/20": 1,
"3/24/20": 1,
"3/25/20": 2,
"3/26/20": 2,
"3/27/20": 2,
"3/28/20": 2,
"3/29/20": 2,
"3/30/20": 2,
"3/31/20": 5,
"4/1/20": 5,
"4/2/20": 10,
"4/3/20": 10,
"4/4/20": 10,
"4/5/20": 15,
"4/6/20": 18,
"4/7/20": 18,
"4/8/20": 29,
"4/9/20": 32,
"4/10/20": 32,
"4/11/20": 32,
"4/12/20": 32,
"4/13/20": 32,
"4/14/20": 40
}
}
}
Output:
// To parse this JSON data, do
//
// final historic = historicFromJson(jsonString);
import 'dart:convert';
Historic historicFromJson(String str) => Historic.fromJson(json.decode(str));
String historicToJson(Historic data) => json.encode(data.toJson());
class Historic {
Historic({
this.country,
this.province,
this.timeline,
});
String country;
dynamic province;
Timeline timeline;
factory Historic.fromJson(Map<String, dynamic> json) => Historic(
country: json["country"],
province: json["province"],
timeline: Timeline.fromJson(json["timeline"]),
);
Map<String, dynamic> toJson() => {
"country": country,
"province": province,
"timeline": timeline.toJson(),
};
}
class Timeline {
Timeline({
this.cases,
this.deaths,
this.recovered,
});
Map<String, int> cases;
Map<String, int> deaths;
Map<String, int> recovered;
factory Timeline.fromJson(Map<String, dynamic> json) => Timeline(
cases: Map.from(json["cases"]).map((k, v) => MapEntry<String, int>(k, v)),
deaths: Map.from(json["deaths"]).map((k, v) => MapEntry<String, int>(k, v)),
recovered: Map.from(json["recovered"]).map((k, v) => MapEntry<String, int>(k, v)),
);
Map<String, dynamic> toJson() => {
"cases": Map.from(cases).map((k, v) => MapEntry<String, dynamic>(k, v)),
"deaths": Map.from(deaths).map((k, v) => MapEntry<String, dynamic>(k, v)),
"recovered": Map.from(recovered).map((k, v) => MapEntry<String, dynamic>(k, v)),
};
}
Related
I need to send request with groovy HTTPBuilder, here is code:
String authToken = "token"
def cfManager = ComponentAccessor.getCustomFieldManager()
def addressJira = "http://xxx"
def http = new HTTPBuilder("${address}")
http.setClient(HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build())
try {
http.request(POST, ContentType.JSON) {
headers.'Authorization' = "token ${authToken}"
headers.'Content-Type' = 'application/json'
headers.'cache-control' = 'no-cache'
body = [
"request": [
"token":"${authToken}",
"commonData":[
"taskId":"${issue.id.toString()}"
],
"phonesData":[
"phone":"${cfManager.getCustomFieldObject("customfield_xxx")?.getValue(issue)?.toString()}",
"phoneType": 1
],
"addData": [
"title":"${issue.summary.toString()}",
"description":"${issue.description.toString()}"
]
]
]
requestContentType = ContentType.JSON
response.success = { resp, json ->
log.info("Resp status " + resp.status.toString())
log.info("JSON ${json.toString()}")
log.info("JSON text ${json.text}")
}
response.failure = { resp ->
log.warn("response code is : " + resp.status.toString())
log.warn("response is : " + resp.getEntity().getContent().getText())
}
}
} catch (Exception e) {
log.warn("Exceptiion while request" + e)
}
I get resp code 200 but on the other side they get JSON like this and can't parse it because of "valueCount", "strings" and "bytes":
{
"request": {
"token": {
"valueCount": 1,
"strings": ["", ""],
"bytes": [85, 69, 108, 112, 108, 120, 90, 99, 113, 107, 100, 106, 71, 108, 121, 102, 199, 115, 103, 107, 33, 45, 109, 70, 37, 65, 91, 33, 47, 77, 54, 83, 111, 115, 77, 49, 77, 50, 107, 74, 65, 122],
"values": ["token"]
},
"commonData": {
"taskId": {
"valueCount": 1,
"strings": ["", ""],
"bytes": [48, 49, 55, 56, 56],
"values": ["here is issue id"]
}
},
"phonesData": {
"phone": {
"valueCount": 1,
"strings": ["", ""],
"bytes": [43, 53, 54, 55, 56, 57, 48],
"values": ["+01234567890"]
},
"phoneType": 1
},
"addData": {
"title": {
"valueCount": 1,
"strings": ["", ""],
"bytes": [84, 101, 115, 116],
"values": ["Test"]
},
"description": {
"valueCount": 1,
"strings": ["", ""],
"bytes": [-113, -48, -78, -48, -70, -48, -80, 32, -48, -76, -48, -69, -47, -113, 32, -48, -102, -48, -90, 32, -48, -98, -48, -73, -48, -66, -48, -67, 46],
"values": ["here is issue summary"]
}
}
}
}
So the question is why they get that parameters and what I have to do not to send that "valueCount", "strings" and "bytes"?
Thanks to any help
The serializer in some versions of Camel does not recognise GString type.
Hence, you would need to force conversion to string by calling toString()
def v_stringvar = "${var1} text ${var2}";
And then you use it in this way
v_stringvar?.toString()
I want to parse a complex JSON in flutter,I have tried many things but I am not clear about the way things are happening.Can anyone explain how do I go about the situation:
{
"message": {
"header": {
"status_code": 200,
"execute_time": 0.021989107131958
},
"body": {
"track_list": [
{
"track": {
"track_id": 200357565,
"track_name": "The Climb Back",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 113835591,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 20,
"album_id": 39278073,
"album_name": "Lewis Street",
"artist_id": 486280,
"artist_name": "J. Cole",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/J-Cole\/The-Climb-Back?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/J-Cole\/The-Climb-Back\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-23T14:02:17Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200187374,
"track_name": "POPSTAR (feat. Drake)",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 113684105,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 6,
"album_id": 39216808,
"album_name": "POPSTAR (feat. Drake) - Single",
"artist_id": 24704782,
"artist_name": "DJ Khaled feat. Drake, Lil Wayne & Rick Ross",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/DJ-Khaled-feat-Drake-Lil-Wayne-Rick-Ross\/POPSTAR-Drake?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/DJ-Khaled-feat-Drake-Lil-Wayne-Rick-Ross\/POPSTAR-Drake\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-17T13:38:30Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200102123,
"track_name": "What's Love Got to Do with It",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 113606423,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 18,
"album_id": 39186667,
"album_name": "What's Love Got to Do with It",
"artist_id": 45989671,
"artist_name": "Kygo feat. Tina Turner",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Kygo-Tina-Turner\/What-s-Love-Got-to-Do-with-It?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Kygo-Tina-Turner\/What-s-Love-Got-to-Do-with-It\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-23T06:28:49Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 194169151,
"track_name": "Blinding Lights",
"track_name_translation_list": [],
"track_rating": 100,
"commontrack_id": 104185748,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 5583,
"album_id": 37216011,
"album_name": "After Hours",
"artist_id": 13937035,
"artist_name": "The Weeknd",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/The-Weeknd-3\/Blinding-Lights?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/The-Weeknd-3\/Blinding-Lights\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-09T11:24:05Z",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_id": 7,
"music_genre_parent_id": 34,
"music_genre_name": "Electronic",
"music_genre_name_extended": "Electronic",
"music_genre_vanity": "Electronic"
}
}
]
}
}
},
{
"track": {
"track_id": 198421234,
"track_name": "Savage Love (Laxed - Siren Beat)",
"track_name_translation_list": [],
"track_rating": 100,
"commontrack_id": 112136372,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 454,
"album_id": 38617941,
"album_name": "Savage Love (Laxed - Siren Beat) - Single",
"artist_id": 45643815,
"artist_name": "Jawsh 685 feat. Jason Derulo",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Jawsh-685-Jason-Derulo\/Savage-Love-Laxed-Siren-Beat?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Jawsh-685-Jason-Derulo\/Savage-Love-Laxed-Siren-Beat\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-09T13:06:43Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 189626475,
"track_name": "Watermelon Sugar",
"track_name_translation_list": [],
"track_rating": 100,
"commontrack_id": 104939195,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 567,
"album_id": 36101498,
"album_name": "Fine Line",
"artist_id": 24505463,
"artist_name": "Harry Styles",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Harry-Styles\/Watermelon-Sugar-2?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Harry-Styles\/Watermelon-Sugar-2\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2019-12-12T16:57:16Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 192324206,
"track_name": "One Margarita",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 107705631,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 62,
"album_id": 36710192,
"album_name": "Born Here Live Here Die Here",
"artist_id": 360257,
"artist_name": "Luke Bryan",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Luke-Bryan\/One-Margarita?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Luke-Bryan\/One-Margarita\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-03-13T08:54:41Z",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_id": 34,
"music_genre_parent_id": 0,
"music_genre_name": "Music",
"music_genre_name_extended": "Music",
"music_genre_vanity": "Music"
}
}
]
}
}
},
{
"track": {
"track_id": 195445553,
"track_name": "ROCKSTAR (feat. Roddy Ricch)",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 109586143,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 687,
"album_id": 37641727,
"album_name": "BLAME IT ON BABY",
"artist_id": 45035319,
"artist_name": "DaBaby feat. Roddy Ricch",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/DaBaby-Roddy-Ricch\/ROCKSTAR-Roddy-Ricch?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/DaBaby-Roddy-Ricch\/ROCKSTAR-Roddy-Ricch\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-06-22T12:43:00Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200340862,
"track_name": "Patience",
"track_name_translation_list": [],
"track_rating": 98,
"commontrack_id": 113824017,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 0,
"num_favourite": 4,
"album_id": 39273295,
"album_name": "Patience",
"artist_id": 156,
"artist_name": "Chris Cornell",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Chris-Cornell\/Patience?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Chris-Cornell\/Patience\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-21T20:15:22Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200360270,
"track_name": "Say Something",
"track_name_translation_list": [],
"track_rating": 1,
"commontrack_id": 113837622,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 0,
"num_favourite": 0,
"album_id": 39278673,
"album_name": "DISCO (Deluxe)",
"artist_id": 7712,
"artist_name": "Kylie Minogue",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Kylie-Minogue\/Say-Something?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Kylie-Minogue\/Say-Something\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-23T16:04:00Z",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_id": 34,
"music_genre_parent_id": 0,
"music_genre_name": "Music",
"music_genre_name_extended": "Music",
"music_genre_vanity": "Music"
}
}
]
}
}
}
]
}
}
}
I used https://app.quicktype.io/ to get something like this:
// To parse this JSON data, do
//
// final jsonToDart = jsonToDartFromMap(jsonString);
import 'dart:convert';
JsonToDart jsonToDartFromMap(String str) => JsonToDart.fromMap(json.decode(str));
String jsonToDartToMap(JsonToDart data) => json.encode(data.toMap());
class JsonToDart {
JsonToDart({
this.message,
});
Message message;
factory JsonToDart.fromMap(Map<String, dynamic> json) => JsonToDart(
message: Message.fromMap(json["message"]),
);
Map<String, dynamic> toMap() => {
"message": message.toMap(),
};
}
class Message {
Message({
this.header,
this.body,
});
Header header;
Body body;
factory Message.fromMap(Map<String, dynamic> json) => Message(
header: Header.fromMap(json["header"]),
body: Body.fromMap(json["body"]),
);
Map<String, dynamic> toMap() => {
"header": header.toMap(),
"body": body.toMap(),
};
}
class Body {
Body({
this.trackList,
});
List<TrackList> trackList;
factory Body.fromMap(Map<String, dynamic> json) => Body(
trackList: List<TrackList>.from(json["track_list"].map((x) => TrackList.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"track_list": List<dynamic>.from(trackList.map((x) => x.toMap())),
};
}
class TrackList {
TrackList({
this.track,
});
Track track;
factory TrackList.fromMap(Map<String, dynamic> json) => TrackList(
track: Track.fromMap(json["track"]),
);
Map<String, dynamic> toMap() => {
"track": track.toMap(),
};
}
class Track {
Track({
this.trackId,
this.trackName,
this.trackNameTranslationList,
this.trackRating,
this.commontrackId,
this.instrumental,
this.explicit,
this.hasLyrics,
this.hasSubtitles,
this.hasRichsync,
this.numFavourite,
this.albumId,
this.albumName,
this.artistId,
this.artistName,
this.trackShareUrl,
this.trackEditUrl,
this.restricted,
this.updatedTime,
this.primaryGenres,
});
int trackId;
String trackName;
List<dynamic> trackNameTranslationList;
int trackRating;
int commontrackId;
int instrumental;
int explicit;
int hasLyrics;
int hasSubtitles;
int hasRichsync;
int numFavourite;
int albumId;
String albumName;
int artistId;
String artistName;
String trackShareUrl;
String trackEditUrl;
int restricted;
DateTime updatedTime;
PrimaryGenres primaryGenres;
factory Track.fromMap(Map<String, dynamic> json) => Track(
trackId: json["track_id"],
trackName: json["track_name"],
trackNameTranslationList: List<dynamic>.from(json["track_name_translation_list"].map((x) => x)),
trackRating: json["track_rating"],
commontrackId: json["commontrack_id"],
instrumental: json["instrumental"],
explicit: json["explicit"],
hasLyrics: json["has_lyrics"],
hasSubtitles: json["has_subtitles"],
hasRichsync: json["has_richsync"],
numFavourite: json["num_favourite"],
albumId: json["album_id"],
albumName: json["album_name"],
artistId: json["artist_id"],
artistName: json["artist_name"],
trackShareUrl: json["track_share_url"],
trackEditUrl: json["track_edit_url"],
restricted: json["restricted"],
updatedTime: DateTime.parse(json["updated_time"]),
primaryGenres: PrimaryGenres.fromMap(json["primary_genres"]),
);
Map<String, dynamic> toMap() => {
"track_id": trackId,
"track_name": trackName,
"track_name_translation_list": List<dynamic>.from(trackNameTranslationList.map((x) => x)),
"track_rating": trackRating,
"commontrack_id": commontrackId,
"instrumental": instrumental,
"explicit": explicit,
"has_lyrics": hasLyrics,
"has_subtitles": hasSubtitles,
"has_richsync": hasRichsync,
"num_favourite": numFavourite,
"album_id": albumId,
"album_name": albumName,
"artist_id": artistId,
"artist_name": artistName,
"track_share_url": trackShareUrl,
"track_edit_url": trackEditUrl,
"restricted": restricted,
"updated_time": updatedTime.toIso8601String(),
"primary_genres": primaryGenres.toMap(),
};
}
class PrimaryGenres {
PrimaryGenres({
this.musicGenreList,
});
List<MusicGenreList> musicGenreList;
factory PrimaryGenres.fromMap(Map<String, dynamic> json) => PrimaryGenres(
musicGenreList: List<MusicGenreList>.from(json["music_genre_list"].map((x) => MusicGenreList.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"music_genre_list": List<dynamic>.from(musicGenreList.map((x) => x.toMap())),
};
}
class MusicGenreList {
MusicGenreList({
this.musicGenre,
});
MusicGenre musicGenre;
factory MusicGenreList.fromMap(Map<String, dynamic> json) => MusicGenreList(
musicGenre: MusicGenre.fromMap(json["music_genre"]),
);
Map<String, dynamic> toMap() => {
"music_genre": musicGenre.toMap(),
};
}
class MusicGenre {
MusicGenre({
this.musicGenreId,
this.musicGenreParentId,
this.musicGenreName,
this.musicGenreNameExtended,
this.musicGenreVanity,
});
int musicGenreId;
int musicGenreParentId;
String musicGenreName;
String musicGenreNameExtended;
String musicGenreVanity;
factory MusicGenre.fromMap(Map<String, dynamic> json) => MusicGenre(
musicGenreId: json["music_genre_id"],
musicGenreParentId: json["music_genre_parent_id"],
musicGenreName: json["music_genre_name"],
musicGenreNameExtended: json["music_genre_name_extended"],
musicGenreVanity: json["music_genre_vanity"],
);
Map<String, dynamic> toMap() => {
"music_genre_id": musicGenreId,
"music_genre_parent_id": musicGenreParentId,
"music_genre_name": musicGenreName,
"music_genre_name_extended": musicGenreNameExtended,
"music_genre_vanity": musicGenreVanity,
};
}
class Header {
Header({
this.statusCode,
this.executeTime,
});
int statusCode;
double executeTime;
factory Header.fromMap(Map<String, dynamic> json) => Header(
statusCode: json["status_code"],
executeTime: json["execute_time"].toDouble(),
);
Map<String, dynamic> toMap() => {
"status_code": statusCode,
"execute_time": executeTime,
};
}
I used this in the main function:
Future<JsonToDart> getData() async {
var response = await http.get(url1);
print("ssssssssssssssss");
print(response.body);
return jsonToDartFromMap(response.body);
}
But I dont know how to proceed from here. I have to take the values of trackId,trackName,artistName,albumName and display in a listView.Many tutorials have different styles and this JSON data I just can't understand how to simplify it.Please help
Just check out the Example that I have created :
This is the json you provided
{
"message": {
"header": {
"status_code": 200,
"execute_time": 0.021989107131958
},
"body": {
"track_list": [
{
"track": {
"track_id": 200357565,
"track_name": "The Climb Back",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 113835591,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 20,
"album_id": 39278073,
"album_name": "Lewis Street",
"artist_id": 486280,
"artist_name": "J. Cole",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/J-Cole\/The-Climb-Back?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/J-Cole\/The-Climb-Back\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-23T14:02:17Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200187374,
"track_name": "POPSTAR (feat. Drake)",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 113684105,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 6,
"album_id": 39216808,
"album_name": "POPSTAR (feat. Drake) - Single",
"artist_id": 24704782,
"artist_name": "DJ Khaled feat. Drake, Lil Wayne & Rick Ross",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/DJ-Khaled-feat-Drake-Lil-Wayne-Rick-Ross\/POPSTAR-Drake?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/DJ-Khaled-feat-Drake-Lil-Wayne-Rick-Ross\/POPSTAR-Drake\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-17T13:38:30Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200102123,
"track_name": "What's Love Got to Do with It",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 113606423,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 18,
"album_id": 39186667,
"album_name": "What's Love Got to Do with It",
"artist_id": 45989671,
"artist_name": "Kygo feat. Tina Turner",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Kygo-Tina-Turner\/What-s-Love-Got-to-Do-with-It?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Kygo-Tina-Turner\/What-s-Love-Got-to-Do-with-It\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-23T06:28:49Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 194169151,
"track_name": "Blinding Lights",
"track_name_translation_list": [],
"track_rating": 100,
"commontrack_id": 104185748,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 5583,
"album_id": 37216011,
"album_name": "After Hours",
"artist_id": 13937035,
"artist_name": "The Weeknd",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/The-Weeknd-3\/Blinding-Lights?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/The-Weeknd-3\/Blinding-Lights\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-09T11:24:05Z",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_id": 7,
"music_genre_parent_id": 34,
"music_genre_name": "Electronic",
"music_genre_name_extended": "Electronic",
"music_genre_vanity": "Electronic"
}
}
]
}
}
},
{
"track": {
"track_id": 198421234,
"track_name": "Savage Love (Laxed - Siren Beat)",
"track_name_translation_list": [],
"track_rating": 100,
"commontrack_id": 112136372,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 454,
"album_id": 38617941,
"album_name": "Savage Love (Laxed - Siren Beat) - Single",
"artist_id": 45643815,
"artist_name": "Jawsh 685 feat. Jason Derulo",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Jawsh-685-Jason-Derulo\/Savage-Love-Laxed-Siren-Beat?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Jawsh-685-Jason-Derulo\/Savage-Love-Laxed-Siren-Beat\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-09T13:06:43Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 189626475,
"track_name": "Watermelon Sugar",
"track_name_translation_list": [],
"track_rating": 100,
"commontrack_id": 104939195,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 567,
"album_id": 36101498,
"album_name": "Fine Line",
"artist_id": 24505463,
"artist_name": "Harry Styles",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Harry-Styles\/Watermelon-Sugar-2?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Harry-Styles\/Watermelon-Sugar-2\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2019-12-12T16:57:16Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 192324206,
"track_name": "One Margarita",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 107705631,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 62,
"album_id": 36710192,
"album_name": "Born Here Live Here Die Here",
"artist_id": 360257,
"artist_name": "Luke Bryan",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Luke-Bryan\/One-Margarita?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Luke-Bryan\/One-Margarita\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-03-13T08:54:41Z",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_id": 34,
"music_genre_parent_id": 0,
"music_genre_name": "Music",
"music_genre_name_extended": "Music",
"music_genre_vanity": "Music"
}
}
]
}
}
},
{
"track": {
"track_id": 195445553,
"track_name": "ROCKSTAR (feat. Roddy Ricch)",
"track_name_translation_list": [],
"track_rating": 99,
"commontrack_id": 109586143,
"instrumental": 0,
"explicit": 1,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 687,
"album_id": 37641727,
"album_name": "BLAME IT ON BABY",
"artist_id": 45035319,
"artist_name": "DaBaby feat. Roddy Ricch",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/DaBaby-Roddy-Ricch\/ROCKSTAR-Roddy-Ricch?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/DaBaby-Roddy-Ricch\/ROCKSTAR-Roddy-Ricch\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-06-22T12:43:00Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200340862,
"track_name": "Patience",
"track_name_translation_list": [],
"track_rating": 98,
"commontrack_id": 113824017,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 0,
"num_favourite": 4,
"album_id": 39273295,
"album_name": "Patience",
"artist_id": 156,
"artist_name": "Chris Cornell",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Chris-Cornell\/Patience?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Chris-Cornell\/Patience\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-21T20:15:22Z",
"primary_genres": {
"music_genre_list": []
}
}
},
{
"track": {
"track_id": 200360270,
"track_name": "Say Something",
"track_name_translation_list": [],
"track_rating": 1,
"commontrack_id": 113837622,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 0,
"num_favourite": 0,
"album_id": 39278673,
"album_name": "DISCO (Deluxe)",
"artist_id": 7712,
"artist_name": "Kylie Minogue",
"track_share_url": "https:\/\/www.musixmatch.com\/lyrics\/Kylie-Minogue\/Say-Something?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"track_edit_url": "https:\/\/www.musixmatch.com\/lyrics\/Kylie-Minogue\/Say-Something\/edit?utm_source=application&utm_campaign=api&utm_medium=n%2Fa%3A1409620463618",
"restricted": 0,
"updated_time": "2020-07-23T16:04:00Z",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_id": 34,
"music_genre_parent_id": 0,
"music_genre_name": "Music",
"music_genre_name_extended": "Music",
"music_genre_vanity": "Music"
}
}
]
}
}
}
]
}
}
}
This is the model for the json :
// To parse this JSON data, do
//
// final track = trackFromJson(jsonString);
import 'dart:convert';
Track trackFromJson(String str) => Track.fromJson(json.decode(str));
String trackToJson(Track data) => json.encode(data.toJson());
class Track {
Track({
this.message,
});
Message message;
factory Track.fromJson(Map<String, dynamic> json) => Track(
message: Message.fromJson(json["message"]),
);
Map<String, dynamic> toJson() => {
"message": message.toJson(),
};
}
class Message {
Message({
this.header,
this.body,
});
Header header;
Body body;
factory Message.fromJson(Map<String, dynamic> json) => Message(
header: Header.fromJson(json["header"]),
body: Body.fromJson(json["body"]),
);
Map<String, dynamic> toJson() => {
"header": header.toJson(),
"body": body.toJson(),
};
}
class Body {
Body({
this.trackList,
});
List<TrackList> trackList;
factory Body.fromJson(Map<String, dynamic> json) => Body(
trackList: List<TrackList>.from(json["track_list"].map((x) => TrackList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"track_list": List<dynamic>.from(trackList.map((x) => x.toJson())),
};
}
class TrackList {
TrackList({
this.track,
});
TrackClass track;
factory TrackList.fromJson(Map<String, dynamic> json) => TrackList(
track: TrackClass.fromJson(json["track"]),
);
Map<String, dynamic> toJson() => {
"track": track.toJson(),
};
}
class TrackClass {
TrackClass({
this.trackId,
this.trackName,
this.trackNameTranslationList,
this.trackRating,
this.commontrackId,
this.instrumental,
this.explicit,
this.hasLyrics,
this.hasSubtitles,
this.hasRichsync,
this.numFavourite,
this.albumId,
this.albumName,
this.artistId,
this.artistName,
this.trackShareUrl,
this.trackEditUrl,
this.restricted,
this.updatedTime,
this.primaryGenres,
});
int trackId;
String trackName;
List<dynamic> trackNameTranslationList;
int trackRating;
int commontrackId;
int instrumental;
int explicit;
int hasLyrics;
int hasSubtitles;
int hasRichsync;
int numFavourite;
int albumId;
String albumName;
int artistId;
String artistName;
String trackShareUrl;
String trackEditUrl;
int restricted;
DateTime updatedTime;
PrimaryGenres primaryGenres;
factory TrackClass.fromJson(Map<String, dynamic> json) => TrackClass(
trackId: json["track_id"],
trackName: json["track_name"],
trackNameTranslationList: List<dynamic>.from(json["track_name_translation_list"].map((x) => x)),
trackRating: json["track_rating"],
commontrackId: json["commontrack_id"],
instrumental: json["instrumental"],
explicit: json["explicit"],
hasLyrics: json["has_lyrics"],
hasSubtitles: json["has_subtitles"],
hasRichsync: json["has_richsync"],
numFavourite: json["num_favourite"],
albumId: json["album_id"],
albumName: json["album_name"],
artistId: json["artist_id"],
artistName: json["artist_name"],
trackShareUrl: json["track_share_url"],
trackEditUrl: json["track_edit_url"],
restricted: json["restricted"],
updatedTime: DateTime.parse(json["updated_time"]),
primaryGenres: PrimaryGenres.fromJson(json["primary_genres"]),
);
Map<String, dynamic> toJson() => {
"track_id": trackId,
"track_name": trackName,
"track_name_translation_list": List<dynamic>.from(trackNameTranslationList.map((x) => x)),
"track_rating": trackRating,
"commontrack_id": commontrackId,
"instrumental": instrumental,
"explicit": explicit,
"has_lyrics": hasLyrics,
"has_subtitles": hasSubtitles,
"has_richsync": hasRichsync,
"num_favourite": numFavourite,
"album_id": albumId,
"album_name": albumName,
"artist_id": artistId,
"artist_name": artistName,
"track_share_url": trackShareUrl,
"track_edit_url": trackEditUrl,
"restricted": restricted,
"updated_time": updatedTime.toIso8601String(),
"primary_genres": primaryGenres.toJson(),
};
}
class PrimaryGenres {
PrimaryGenres({
this.musicGenreList,
});
List<MusicGenreList> musicGenreList;
factory PrimaryGenres.fromJson(Map<String, dynamic> json) => PrimaryGenres(
musicGenreList: List<MusicGenreList>.from(json["music_genre_list"].map((x) => MusicGenreList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"music_genre_list": List<dynamic>.from(musicGenreList.map((x) => x.toJson())),
};
}
class MusicGenreList {
MusicGenreList({
this.musicGenre,
});
MusicGenre musicGenre;
factory MusicGenreList.fromJson(Map<String, dynamic> json) => MusicGenreList(
musicGenre: MusicGenre.fromJson(json["music_genre"]),
);
Map<String, dynamic> toJson() => {
"music_genre": musicGenre.toJson(),
};
}
class MusicGenre {
MusicGenre({
this.musicGenreId,
this.musicGenreParentId,
this.musicGenreName,
this.musicGenreNameExtended,
this.musicGenreVanity,
});
int musicGenreId;
int musicGenreParentId;
String musicGenreName;
String musicGenreNameExtended;
String musicGenreVanity;
factory MusicGenre.fromJson(Map<String, dynamic> json) => MusicGenre(
musicGenreId: json["music_genre_id"],
musicGenreParentId: json["music_genre_parent_id"],
musicGenreName: json["music_genre_name"],
musicGenreNameExtended: json["music_genre_name_extended"],
musicGenreVanity: json["music_genre_vanity"],
);
Map<String, dynamic> toJson() => {
"music_genre_id": musicGenreId,
"music_genre_parent_id": musicGenreParentId,
"music_genre_name": musicGenreName,
"music_genre_name_extended": musicGenreNameExtended,
"music_genre_vanity": musicGenreVanity,
};
}
class Header {
Header({
this.statusCode,
this.executeTime,
});
int statusCode;
double executeTime;
factory Header.fromJson(Map<String, dynamic> json) => Header(
statusCode: json["status_code"],
executeTime: json["execute_time"].toDouble(),
);
Map<String, dynamic> toJson() => {
"status_code": statusCode,
"execute_time": executeTime,
};
}
This is the ui for the model:
import 'package:flutter/material.dart';
import 'package:json_parsing_example/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<TrackList> trackList = List();
bool _isLoading = false;
#override
void initState() {
super.initState();
getData();
}
getData() async {
setState(() {
_isLoading = true;
});
String data =
await DefaultAssetBundle.of(context).loadString("json/parse.json");
final track = trackFromJson(data);
trackList = track.message.body.trackList;
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _isLoading
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: trackList.length,
itemBuilder: (context, index) {
var item = trackList[index];
return Card(
margin: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Track Id :' + item.track.trackId.toString()),
Text('Track Name:' + item.track.trackName.toString()),
Text(
'Artist Name :' + item.track.artistName.toString()),
Text('Album Name :' + item.track.albumName.toString())
],
),
);
}));
}
}
From the function what I see is you can do like this:
Future<List<TrackList>> getData() async {
var response = await http.get(url1);
print("ssssssssssssssss");
print(response.body);
var item = trackFromJson(response.body);
return item.body.track_list;
}
Check out the example and let me know if it works.
The way to do it is to create your own model classes in which you perform parsing mechanism. One of the examples would be user class created like this:
class User {
String firstName;
String lastName;
String phoneNumber;
String emailAddress;
User({
this.firstName,
this.lastName,
this.phoneNumber,
this.emailAddress,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
firstName: json["first_name"],
lastName: json["last_name"],
phoneNumber: json["phone_number"],
emailAddress: json["email_address"],
);
}
}
After you are done creating your base model that holds entire tree you posted above, you go ahead and start parsing array elements such as track_list by creating Track model listing all the track properties. Once you have your base model, Track model and all the properties of the Track model, you would need to link that track list to your base model and it's done like this:
List jsonList = json.decode(serverResponse.body)['track_list'];
trackList: List.generate(jsonList.length, (i) => Track.fromJson(jsonList[i]));
When you complete linking base model, list of tracks and parsing of a single track, you will also need to parse inner Track lists in the same way, but basics of the parsing mechanism I listed above should be enough to get you through the entire process of parsing JSON object and JSON inner list objects.
Simple JSON data fetch and show in screen the data is showing in print but while showing in screen its giving error of NoSuchMethodErrorClass 'ResponsiveObjectSettingByUser' has no instance method 'car' receiver: Instance,
GET FUNCTION
Future<ResponseObjectSettingByUser> _list;
final String _url = '<LINK>';
Future<ResponseObjectSettingByUser> getUserSettings() async {
ResponseObjectSettingByUser responseData = null;
var response = await http
.get(_url + '<link>', headers: {
"Authorization":
'Bearer <TOKEN>',
});
var responseJson = json.decode(response.body);
if (response.statusCode == 200) {
responseJson = settingByUserModel(response.body);
print(responseJson.toJson().toString());
}
return responseJson;
}
Initilize
#override
void initState() {
super.initState();
_list = getUserSettings();
}
MODEL CLASS (ResponseObjectSettingByUser)
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
ResponseObjectSettingByUser settingByUserModel(String str) => ResponseObjectSettingByUser.fromJson(json.decode(str));
String welcomeToJson(ResponseObjectSettingByUser data) => json.encode(data.toJson());
class ResponseObjectSettingByUser {
ResponseObjectSettingByUser({
this.array,
});
Array array;
factory ResponseObjectSettingByUser.fromJson(Map<String, dynamic> json) => ResponseObjectSettingByUser(
array: Array.fromJson(json["array"]),
);
Map<String, dynamic> toJson() => {
"array": array.toJson(),
};
}
class Array {
Array({
this.car,
});
List<Car> car;
factory Array.fromJson(Map<String, dynamic> json) => Array(
car: List<Car>.from(json["car"].map((x) => Car.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"car": List<dynamic>.from(car.map((x) => x.toJson())),
};
}
class Car {
Car({
this.id,
this.name,
this.numberKmsMin,
this.numberKmsMax,
this.priceMin,
this.priceMax,
this.powerHorseMin,
this.powerHorseMax,
this.status,
this.isSaved,
this.markId,
this.markName,
this.markImageUrl,
this.modelId,
this.modelName,
this.modelImageUrl,
this.bodyworkId,
this.bodyworkName,
this.fuelId,
this.fuelName,
this.motorizationId,
this.motorizationName,
this.rimsId,
this.rimsName,
this.serieId,
this.serieName,
this.interiorEquipmentId,
this.interiorEquipmentName,
this.upholsteryId,
this.upholsteryName,
this.upholsteryLeatherFabricName,
this.iluminationId,
this.iluminationName,
this.externalEquipmentId,
this.externalEquipmentName,
this.dateStartMin,
this.dateEndMax,
this.settings,
});
int id;
String name;
String numberKmsMin;
String numberKmsMax;
String priceMin;
String priceMax;
String powerHorseMin;
String powerHorseMax;
String status;
int isSaved;
int markId;
String markName;
String markImageUrl;
int modelId;
String modelName;
String modelImageUrl;
int bodyworkId;
String bodyworkName;
int fuelId;
String fuelName;
int motorizationId;
String motorizationName;
dynamic rimsId;
dynamic rimsName;
int serieId;
String serieName;
int interiorEquipmentId;
String interiorEquipmentName;
int upholsteryId;
String upholsteryName;
String upholsteryLeatherFabricName;
int iluminationId;
String iluminationName;
int externalEquipmentId;
String externalEquipmentName;
String dateStartMin;
String dateEndMax;
List<Setting> settings;
factory Car.fromJson(Map<String, dynamic> json) => Car(
id: json["id"],
name: json["name"],
numberKmsMin: json["number_kms_min"],
numberKmsMax: json["number_kms_max"],
priceMin: json["price_min"],
priceMax: json["price_max"],
powerHorseMin: json["power_horse_min"],
powerHorseMax: json["power_horse_max"],
status: json["status"],
isSaved: json["is_saved"],
markId: json["mark_id"],
markName: json["mark_name"],
markImageUrl: json["mark_image_url"],
modelId: json["model_id"],
modelName: json["model_name"],
modelImageUrl: json["model_image_url"],
bodyworkId: json["bodywork_id"],
bodyworkName: json["bodywork_name"],
fuelId: json["fuel_id"],
fuelName: json["fuel_name"],
motorizationId: json["Motorization_id"],
motorizationName: json["Motorization_name"],
rimsId: json["rims_id"],
rimsName: json["rims_name"],
serieId: json["serie_id"],
serieName: json["serie_name"],
interiorEquipmentId: json["Interior_equipment_id"],
interiorEquipmentName: json["Interior_equipment_name"],
upholsteryId: json["Upholstery_id"],
upholsteryName: json["Upholstery_name"],
upholsteryLeatherFabricName: json["Upholstery_Leather_fabric_name"],
iluminationId: json["ilumination_id"],
iluminationName: json["ilumination_name"],
externalEquipmentId: json["external_equipment_id"],
externalEquipmentName: json["external_equipment_name"],
dateStartMin: json["date_start_min"],
dateEndMax: json["date_end_max"],
settings: json["settings"] == null ? null : List<Setting>.from(json["settings"].map((x) => Setting.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"number_kms_min": numberKmsMin,
"number_kms_max": numberKmsMax,
"price_min": priceMin,
"price_max": priceMax,
"power_horse_min": powerHorseMin,
"power_horse_max": powerHorseMax,
"status": status,
"is_saved": isSaved,
"mark_id": markId,
"mark_name": markName,
"mark_image_url": markImageUrl,
"model_id": modelId,
"model_name": modelName,
"model_image_url": modelImageUrl,
"bodywork_id": bodyworkId,
"bodywork_name": bodyworkName,
"fuel_id": fuelId,
"fuel_name": fuelName,
"Motorization_id": motorizationId,
"Motorization_name": motorizationName,
"rims_id": rimsId,
"rims_name": rimsName,
"serie_id": serieId,
"serie_name": serieName,
"Interior_equipment_id": interiorEquipmentId,
"Interior_equipment_name": interiorEquipmentName,
"Upholstery_id": upholsteryId,
"Upholstery_name": upholsteryName,
"Upholstery_Leather_fabric_name": upholsteryLeatherFabricName,
"ilumination_id": iluminationId,
"ilumination_name": iluminationName,
"external_equipment_id": externalEquipmentId,
"external_equipment_name": externalEquipmentName,
"date_start_min": dateStartMin,
"date_end_max": dateEndMax,
"settings": settings == null ? null : List<dynamic>.from(settings.map((x) => x.toJson())),
};
}
class Setting {
Setting({
this.id,
this.name,
});
int id;
String name;
factory Setting.fromJson(Map<String, dynamic> json) => Setting(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
To show data on screen using
child: FutureBuilder(
future: getUserSettings(),
builder: (BuildContext context,
AsyncSnapshot snapshot) {
final countries = snapshot.data;
if (snapshot.data == null) {
//IF NULL
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return Stack(
children: [
Container(
child: Text(snapshot.data.Car[0].id)
),
),
],
);
}
},
),
JSON Data is like this.
{
"array": {
"car": [
{
"id": 131,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 121,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 111,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
}
]
}
}
You can copy paste run full code below
You can use AsyncSnapshot<ResponseObjectSettingByUser> and check connectionState and use snapshot.data.array.car.length in ListView
code snippet
FutureBuilder(
future: _list,
builder:
(context, AsyncSnapshot<ResponseObjectSettingByUser> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.array.car.length,
itemBuilder: (context, index) {
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
ResponseObjectSettingByUser settingByUserModel(String str) =>
ResponseObjectSettingByUser.fromJson(json.decode(str));
String welcomeToJson(ResponseObjectSettingByUser data) =>
json.encode(data.toJson());
class ResponseObjectSettingByUser {
ResponseObjectSettingByUser({
this.array,
});
Array array;
factory ResponseObjectSettingByUser.fromJson(Map<String, dynamic> json) =>
ResponseObjectSettingByUser(
array: Array.fromJson(json["array"]),
);
Map<String, dynamic> toJson() => {
"array": array.toJson(),
};
}
class Array {
Array({
this.car,
});
List<Car> car;
factory Array.fromJson(Map<String, dynamic> json) => Array(
car: List<Car>.from(json["car"].map((x) => Car.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"car": List<dynamic>.from(car.map((x) => x.toJson())),
};
}
class Car {
Car({
this.id,
this.name,
this.numberKmsMin,
this.numberKmsMax,
this.priceMin,
this.priceMax,
this.powerHorseMin,
this.powerHorseMax,
this.status,
this.isSaved,
this.markId,
this.markName,
this.markImageUrl,
this.modelId,
this.modelName,
this.modelImageUrl,
this.bodyworkId,
this.bodyworkName,
this.fuelId,
this.fuelName,
this.motorizationId,
this.motorizationName,
this.rimsId,
this.rimsName,
this.serieId,
this.serieName,
this.interiorEquipmentId,
this.interiorEquipmentName,
this.upholsteryId,
this.upholsteryName,
this.upholsteryLeatherFabricName,
this.iluminationId,
this.iluminationName,
this.externalEquipmentId,
this.externalEquipmentName,
this.dateStartMin,
this.dateEndMax,
this.settings,
});
int id;
String name;
String numberKmsMin;
String numberKmsMax;
String priceMin;
String priceMax;
String powerHorseMin;
String powerHorseMax;
String status;
int isSaved;
int markId;
String markName;
String markImageUrl;
int modelId;
String modelName;
String modelImageUrl;
int bodyworkId;
String bodyworkName;
int fuelId;
String fuelName;
int motorizationId;
String motorizationName;
dynamic rimsId;
dynamic rimsName;
int serieId;
String serieName;
int interiorEquipmentId;
String interiorEquipmentName;
int upholsteryId;
String upholsteryName;
String upholsteryLeatherFabricName;
int iluminationId;
String iluminationName;
int externalEquipmentId;
String externalEquipmentName;
String dateStartMin;
String dateEndMax;
List<Setting> settings;
factory Car.fromJson(Map<String, dynamic> json) => Car(
id: json["id"],
name: json["name"],
numberKmsMin: json["number_kms_min"],
numberKmsMax: json["number_kms_max"],
priceMin: json["price_min"],
priceMax: json["price_max"],
powerHorseMin: json["power_horse_min"],
powerHorseMax: json["power_horse_max"],
status: json["status"],
isSaved: json["is_saved"],
markId: json["mark_id"],
markName: json["mark_name"],
markImageUrl: json["mark_image_url"],
modelId: json["model_id"],
modelName: json["model_name"],
modelImageUrl: json["model_image_url"],
bodyworkId: json["bodywork_id"],
bodyworkName: json["bodywork_name"],
fuelId: json["fuel_id"],
fuelName: json["fuel_name"],
motorizationId: json["Motorization_id"],
motorizationName: json["Motorization_name"],
rimsId: json["rims_id"],
rimsName: json["rims_name"],
serieId: json["serie_id"],
serieName: json["serie_name"],
interiorEquipmentId: json["Interior_equipment_id"],
interiorEquipmentName: json["Interior_equipment_name"],
upholsteryId: json["Upholstery_id"],
upholsteryName: json["Upholstery_name"],
upholsteryLeatherFabricName: json["Upholstery_Leather_fabric_name"],
iluminationId: json["ilumination_id"],
iluminationName: json["ilumination_name"],
externalEquipmentId: json["external_equipment_id"],
externalEquipmentName: json["external_equipment_name"],
dateStartMin: json["date_start_min"],
dateEndMax: json["date_end_max"],
settings: json["settings"] == null
? null
: List<Setting>.from(
json["settings"].map((x) => Setting.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"number_kms_min": numberKmsMin,
"number_kms_max": numberKmsMax,
"price_min": priceMin,
"price_max": priceMax,
"power_horse_min": powerHorseMin,
"power_horse_max": powerHorseMax,
"status": status,
"is_saved": isSaved,
"mark_id": markId,
"mark_name": markName,
"mark_image_url": markImageUrl,
"model_id": modelId,
"model_name": modelName,
"model_image_url": modelImageUrl,
"bodywork_id": bodyworkId,
"bodywork_name": bodyworkName,
"fuel_id": fuelId,
"fuel_name": fuelName,
"Motorization_id": motorizationId,
"Motorization_name": motorizationName,
"rims_id": rimsId,
"rims_name": rimsName,
"serie_id": serieId,
"serie_name": serieName,
"Interior_equipment_id": interiorEquipmentId,
"Interior_equipment_name": interiorEquipmentName,
"Upholstery_id": upholsteryId,
"Upholstery_name": upholsteryName,
"Upholstery_Leather_fabric_name": upholsteryLeatherFabricName,
"ilumination_id": iluminationId,
"ilumination_name": iluminationName,
"external_equipment_id": externalEquipmentId,
"external_equipment_name": externalEquipmentName,
"date_start_min": dateStartMin,
"date_end_max": dateEndMax,
"settings": settings == null
? null
: List<dynamic>.from(settings.map((x) => x.toJson())),
};
}
class Setting {
Setting({
this.id,
this.name,
});
int id;
String name;
factory Setting.fromJson(Map<String, dynamic> json) => Setting(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<ResponseObjectSettingByUser> _list;
Future<ResponseObjectSettingByUser> getUserSettings() async {
ResponseObjectSettingByUser responseData = null;
/*var response = await http
.get(_url + '<link>', headers: {
"Authorization":
'Bearer <TOKEN>',
});*/
String jsonString = '''
{
"array": {
"car": [
{
"id": 131,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 121,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
},
{
"id": 111,
"name": "120",
"number_kms_min": "1000",
"number_kms_max": "10000",
"price_min": "10000",
"price_max": "1000",
"power_horse_min": "100",
"power_horse_max": "120",
"status": "1",
"is_saved": 0,
"mark_id": 1,
"mark_name": "BMW",
"mark_image_url": "https://cdn0.iconfinder.com/data/icons/car-brands/550/BMW_logo-512.png",
"model_id": 1,
"model_name": "Serie 1",
"model_image_url": "https://www.bmw.pt/content/dam/bmw/common/all-models/1-series/5-door/2019/navigation/bmw-1-series-modelfinder.png",
"bodywork_id": 1,
"bodywork_name": "Coupé",
"fuel_id": 1,
"fuel_name": "Gasolina",
"Motorization_id": 1,
"Motorization_name": "Manual",
"rims_id": 1,
"rims_name": "Preto fosco\r\n5 raios",
"serie_id": 1,
"serie_name": "120",
"Interior_equipment_id": 1,
"Interior_equipment_name": "Bancos desportivos\r\n",
"Upholstery_id": 1,
"Upholstery_name": "Preto",
"Upholstery_Leather_fabric_name": "Preto",
"ilumination_id": 1,
"ilumination_name": "Iluminação ambiente",
"external_equipment_id": 1,
"external_equipment_name": "Para-choques desportivos",
"date_start_min": "03/18",
"date_end_max": "09/19"
}
]
}
}
''';
http.Response response = http.Response(jsonString, 200);
if (response.statusCode == 200) {
String postProcessing =
response.body.replaceAll('\n', "").replaceAll('\r', "");
var responseJson = settingByUserModel(postProcessing);
print(responseJson.toJson().toString());
return responseJson;
}
}
#override
void initState() {
_list = getUserSettings();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _list,
builder:
(context, AsyncSnapshot<ResponseObjectSettingByUser> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.array.car.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot
.data.array.car[index].markName),
Spacer(),
Text(snapshot
.data.array.car[index].id.toString()),
],
),
));
});
}
}
}));
}
}
Below is the Json which i need to process
var oldArr =
[{
"careerLevel": "Associate",
"careerLevels": [
{
"201609": 21,
"201610": 22,
"careerID": "10000120"
},
{
"201609": 31,
"201610": 32,
"careerID": "10000130"
}]}];
And convert the above json to :
var newArr= [{
"201609": 52,
"201610": 54,
"careerLevel": "Associate",
"careerLevels": [
{
"201609": 21,
"201610": 22,
"careerID": "10000120"
},
{
"201609": 31,
"201610": 32,
"careerID": "10000130"
}]
}];
Iam trying to achieve the summation using reduce() function:
var arr = [{x:1},{x:2},{x:4}];
arr.reduce(function (a, b) {
return {x: a.x + b.x};
});
console.log(arr); //Outputs that same initial array
var reduceArr = oldArr.reduce((sum, item) =>
const total = sum + item.201609; // this gives me error
);
I have some idea about reduce function but i am still new to this stuff.
I dont know why noone attempted this question. Although people were quick to downvote.
I have created below code to get the desired result :
var oldArr =
{
"careerLevel": "Associate",
"careerLevels": [
{
"201609": 21,
"201610": 22,
"201611": 23,
"careerID": "10000120"
},
{
"201609": 31,
"201610": 32,
"201611": 33,
"careerID": "10000130"
}]
};
var finalSummedJson = JSON.stringify(SummationProcessing(oldArr));
return finalSummedJson;
}
// Summation Logic
function SummationProcessing(oldArr) {
let sumArr = [];
let allKeysInLevels = Object.keys(oldArr.careerLevels[0]);
let uniqueKeys = allKeysInLevels.filter((key, index) => {
return parseInt(key) > 0 && allKeysInLevels.indexOf(key) == index
});
uniqueKeys.forEach(uniqueKey => {
var sumKey = oldArr.careerLevels.reduce((acc, val) => {
return acc + val[uniqueKey];
}, 0);
sumArr.push(sumKey);
});
var reducedData = oldArr.careerLevels.reduce((redArr, inpArr) => {
var keysToFilter = Object.keys(inpArr);
var keyysss = keysToFilter.filter((key, index) => { return parseInt(key) > 0 && keysToFilter.indexOf(key) == index });
keyysss.forEach((element, i) => {
if (!redArr[element]) {
redArr[element] = sumArr[i];
}
// });
});
return redArr;
}, {});
// console.log("reducedData", JSON.stringify(reducedData));
Object.keys(reducedData).forEach(key => { oldArr[key] = reducedData[key] });
return oldArr;
// console.log("finalArr", oldArr);
}
The final result was :
{
"201609": 52,
"201610": 54,
"201611": 56,
"careerLevel": "Associate",
"careerLevels": [{
"201609": 21,
"201610": 22,
"201611": 23,
"careerID": "10000120"
}, {
"201609": 31,
"201610": 32,
"201611": 33,
"careerID": "10000130"
}]
}
I've been trying to display a model on my screen (a simple UVSphere from Blender). I first exported it to .fbx format and then transformed to .g3db format with gdx-conv-win32.exe. I have this code so far, but all it shows me is a blank black screen... it only works with the model found in this tutorial (an .obj model) https://xoppa.github.io/blog/loading-models-using-libgdx/
package com.mygdx.game.screens;
/.../ imports
public class GameScreen extends MenuScreens {
public Environment environment;
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public Model model;
public ModelInstance instance;
AssetManager manager = new AssetManager();
public boolean loading;
public Array<ModelInstance> instances;
public GameScreen(ProjectSurvival game){
super();
this.game = game;
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.9f, 0.9f, 0.9f, 20f, 20f, 20f));
environment.add(new PointLight().set(1, 1, 1, 20, 20, 20, 500));
instances = new Array<ModelInstance>();
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(1f, 1f, 1f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
manager = new AssetManager();
manager.load("ship.g3db", Model.class);
loading = true;
}
private void doneLoading() {
Model test = manager.get("ship.g3db", Model.class);
ModelInstance shipInstance = new ModelInstance(test);
instances.add(shipInstance);
loading = false;
}
#Override
public void show() {
}
#Override
public void render(float delta) {
//super.render(delta);
if (loading && manager.update()) {
doneLoading();
System.out.println("loaded");
}
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instances, environment);
modelBatch.end();
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
super.dispose();
modelBatch.dispose();
model.dispose();
instances.clear();
manager.dispose();
}
}
There are several other similar topics, but none of them solves my problem... please I need help!
EDIT:
Here's my g3dj file ( I cut some parts of it cause it's extremely long):
{
"version": [ 0, 1],
"id": "",
"meshes": [
{
"attributes": ["POSITION", "NORMAL", "TEXCOORD0"],
"vertices": [
-0.724124, 0.035572, -0.598984, -0.742302, -0.159337, -0.650807, 0.028780, 0.420519,
-0.691568, 0.068115, -0.634070, -0.791498, -0.084201, -0.605335, 0.021021, 0.407816,
-0.694079, 0.034096, -0.634070, -0.878414, 0.254219, -0.404614, 0.026918, 0.405321,
// deleted (...)
-0.846887, -0.041603, -0.403719, -0.887509, -0.132389, -0.441267, 0.051316, 0.489956,
-0.826199, -0.040587, -0.445113, -0.867977, -0.072359, -0.491256, 0.049283, 0.474874,
-0.803523, -0.039472, -0.485435, -0.859127, -0.022919, -0.511185, 0.047232, 0.459797
],
"parts": [
{
"id": "Mesh_part1",
"type": "TRIANGLES",
"indices": [
0, 1, 2, 1, 0, 3, 4, 2, 5, 2, 4, 0,
2, 6, 7, 6, 2, 1, 5, 7, 8, 7, 5, 2,
0, 9, 3, 3, 9, 10, 9, 11, 10, 11, 9, 12,
9, 4, 13, 4, 9, 0, 12, 13, 14, 13, 12, 9,
// deleted (...)
3610, 3613, 3614, 137, 3614, 3613, 3614, 137, 133, 3606, 3612, 3596,
3612, 3606, 3613, 112, 3613, 3606, 3613, 112, 137, 3614, 3608, 3610,
3608, 3614, 3615, 3615, 3539, 3608, 3539, 3615, 3543, 133, 3615, 3614,
3615, 133, 134, 134, 3543, 3615, 3543, 134, 14
]
}
]
}
],
"materials": [
{
"id": "Material.001",
"ambient": [ 0.200000, 0.200000, 0.200000],
"diffuse": [ 0.800000, 0.800000, 0.800000],
"emissive": [ 0.000000, 0.000000, 0.000000],
"opacity": 0.000000,
"specular": [ 0.200000, 0.200000, 0.200000],
"shininess": 20.000000
}
],
"nodes": [
{
"id": "Sphere",
"rotation": [-0.707107, 0.000000, 0.000000, 0.707107],
"scale": [ 100.000000, 100.000000, 100.000000],
"translation": [ 0.000000, 101.334976, 0.000000],
"parts": [
{
"meshpartid": "Mesh_part1",
"materialid": "Material.001",
"uvMapping": [[]]
}
]
}
],
"animations": []
}
Since there is no accepted answer:
As described by #Xoppa In you file the opacity is set to zero, set it to 1.0000 in the gd3j file
"opacity": 0.000000
// TODO 1: find what is the property of the material in blender
// TODO 2: add to troubleshooting guide
Had the same problem but with converting LWO (Light Wave) objects to g3db / g3dj. Problem was that when LightWave is exporting to FBX format it doesn't add info about textures (I'm not actually sure if FBX format supports textures at all?). Then I switched exporting to .OBJ but again I had the problem that textures in png format are not supported. Only after using .jpg textures it started working. After that opacity was set correctly to 1. With textures it can't handle converter is setting opacity to 0.