How to parse JSON Array of Array of objects - flutter

basically the issue is i am getting cities array and in the cities array i have multiple cities and each city also contain array i need model for this json response i am using "https://app.quicktype.io/"
{
"code": "0",
"message": "Success!",
"data": {
"firstName": "hello",
"lastName": "world",
"mobile1": "123456789",
"mobile2": "123456789",
"cities": [
{
"Dubai": [
{
"id": 17,
"value": "Dubai",
"selected": false
}
]
},
{
"Ajman": [
{
"id": 29,
"value": "Ajman",
"selected": false
}
]
},
{
"Fujairah": [
{
"id": 30,
"value": "Fujairah",
"selected": false
}
]
},
{
"Ras Al Khaimah": [
{
"id": 31,
"value": "Ras Al Khaimah",
"selected": false
}
]
},
{
"Um Ul Quwein": [
{
"id": 32,
"value": "Umm Al Quwein",
"selected": false
}
]
},
{
"AbuDhabi": [
{
"id": 33,
"value": "Al Ain",
"selected": false
},
{
"id": 34,
"value": "Abu Dhabi",
"selected": false
}
]
},
{
"Sharjah": [
{
"id": 35,
"value": "Sharjah",
"selected": true
}
]
}
],
"picture": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png"
}
}

If you are in control of the API I'd highly suggest restructuring the response in such a way that you don't have any dynamic keys. It's much more conventional and also easier to work with. For your example you could change this part
{
"AbuDhabi": [
{
"id": 33,
"value": "Al Ain",
"selected": false
},
{
"id": 34,
"value": "Abu Dhabi",
"selected": false
}
]
}
to
{
"name" : "AbuDhabi",
"cities" : [
{
"id": 33,
"value": "Al Ain",
"selected": false
},
{
"id": 34,
"value": "Abu Dhabi",
"selected": false
}
]
}
And then maybe rename the outer "cities" to "emirates"

Use this JsontoDart to convert json response to Model.

You can use the following website to convert your JSON to POJO class -
https://javiercbk.github.io/json_to_dart/
Your Response class will be like this -
class Response{
String? code;
String? message;
Data? data;
Response({this.code, this.message, this.data});
Response.fromJson(Map<String, dynamic> json) {
code = json['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['code'] = this.code;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data!.toJson();
}
return data;
}
}
class Data {
String? firstName;
String? lastName;
String? mobile1;
String? mobile2;
List<Cities>? cities;
String? picture;
Data(
{this.firstName,
this.lastName,
this.mobile1,
this.mobile2,
this.cities,
this.picture});
Data.fromJson(Map<String, dynamic> json) {
firstName = json['firstName'];
lastName = json['lastName'];
mobile1 = json['mobile1'];
mobile2 = json['mobile2'];
if (json['cities'] != null) {
cities = <Cities>[];
json['cities'].forEach((v) {
cities!.add(new Cities.fromJson(v));
});
}
picture = json['picture'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['firstName'] = this.firstName;
data['lastName'] = this.lastName;
data['mobile1'] = this.mobile1;
data['mobile2'] = this.mobile2;
if (this.cities != null) {
data['cities'] = this.cities!.map((v) => v.toJson()).toList();
}
data['picture'] = this.picture;
return data;
}
}
class Cities {
List<Dubai>? dubai;
List<Ajman>? ajman;
List<Fujairah>? fujairah;
List<RasAlKhaimah>? rasAlKhaimah;
List<UmUlQuwein>? umUlQuwein;
List<AbuDhabi>? abuDhabi;
List<Sharjah>? sharjah;
Cities(
{this.dubai,
this.ajman,
this.fujairah,
this.rasAlKhaimah,
this.umUlQuwein,
this.abuDhabi,
this.sharjah});
Cities.fromJson(Map<String, dynamic> json) {
if (json['Dubai'] != null) {
dubai = <Dubai>[];
json['Dubai'].forEach((v) {
dubai!.add(new Dubai.fromJson(v));
});
}
if (json['Ajman'] != null) {
ajman = <Ajman>[];
json['Ajman'].forEach((v) {
ajman!.add(new Ajman.fromJson(v));
});
}
if (json['Fujairah'] != null) {
fujairah = <Fujairah>[];
json['Fujairah'].forEach((v) {
fujairah!.add(new Fujairah.fromJson(v));
});
}
if (json['Ras Al Khaimah'] != null) {
rasAlKhaimah = <RasAlKhaimah>[];
json['Ras Al Khaimah'].forEach((v) {
rasAlKhaimah!.add(new RasAlKhaimah.fromJson(v));
});
}
if (json['Um Ul Quwein'] != null) {
umUlQuwein = <UmUlQuwein>[];
json['Um Ul Quwein'].forEach((v) {
umUlQuwein!.add(new UmUlQuwein.fromJson(v));
});
}
if (json['AbuDhabi'] != null) {
abuDhabi = <AbuDhabi>[];
json['AbuDhabi'].forEach((v) {
abuDhabi!.add(new AbuDhabi.fromJson(v));
});
}
if (json['Sharjah'] != null) {
sharjah = <Sharjah>[];
json['Sharjah'].forEach((v) {
sharjah!.add(new Sharjah.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.dubai != null) {
data['Dubai'] = this.dubai!.map((v) => v.toJson()).toList();
}
if (this.ajman != null) {
data['Ajman'] = this.ajman!.map((v) => v.toJson()).toList();
}
if (this.fujairah != null) {
data['Fujairah'] = this.fujairah!.map((v) => v.toJson()).toList();
}
if (this.rasAlKhaimah != null) {
data['Ras Al Khaimah'] =
this.rasAlKhaimah!.map((v) => v.toJson()).toList();
}
if (this.umUlQuwein != null) {
data['Um Ul Quwein'] = this.umUlQuwein!.map((v) => v.toJson()).toList();
}
if (this.abuDhabi != null) {
data['AbuDhabi'] = this.abuDhabi!.map((v) => v.toJson()).toList();
}
if (this.sharjah != null) {
data['Sharjah'] = this.sharjah!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Dubai {
int? id;
String? value;
bool? selected;
Dubai({this.id, this.value, this.selected});
Dubai.fromJson(Map<String, dynamic> json) {
id = json['id'];
value = json['value'];
selected = json['selected'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['value'] = this.value;
data['selected'] = this.selected;
return data;
}
}

Related

How to make complex Model for my Flutter Dart Project?

I need to create a dart Model class for this complex json .Please any one help
{
"status": "1",
"list": {
"4": [
{
"id": "1289",
"t": "Mutton biriyani",
"p": "21",
"i": "1289_5305.jpg",
"v": "0"
},
{
"id": "1288",
"t": "Chicken biriyani",
"p": "14",
"i": "1288_5339.jpg",
"v": "0"
}
]
}
}
can any one help
you can create modal of every json using this website json-to-dart.
and after making some changes the modal for your jsong would be something like this
class Modal {
String? status;
List<FoodList>? foodList;
Modal({this.status, this.foodList});
Modal.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['list']["4"] != null) {
foodList = <FoodList>[];
json['list']["4"].forEach((v) {
foodList!.add(new FoodList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.foodList != null) {
data['list']["4"] = this.foodList!.map((v) => v.toJson()).toList();
}
return data;
}
}
class FoodList {
String? id;
String? t;
String? p;
String? i;
String? v;
FoodList({this.id, this.t, this.p, this.i, this.v});
FoodList.fromJson(Map<String, dynamic> json) {
id = json['id'];
t = json['t'];
p = json['p'];
i = json['i'];
v = json['v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['t'] = this.t;
data['p'] = this.p;
data['i'] = this.i;
data['v'] = this.v;
return data;
}
}
Here is an example of a Dart Model class that could be used to parse the JSON you provided
class Model {
final String status;
final List list;
Model({this.status, this.list});
factory Model.fromJson(Map<String, dynamic> json) {
return Model(
status: json['status'],
list: json['list'],
);
}
}
And you can use it like this
final jsonString = '{ "status": "1", "list": { "4": [ { "id": "1289", "t": "Mutton biriyani", "p": "21", "i": "1289_5305.jpg", "v": "0" }, { "id": "1288", "t": "Chicken biriyani", "p": "14", "i": "1288_5339.jpg", "v": "0" } ] } }';
final jsonMap = jsonDecode(jsonString);
final data = Model.fromJson(jsonMap);
Note that the List class is a basic type in dart, so it is not suitable for your json structure. In this case, you need to define a custom class for the "list" field.
class FoodList {
String status;
Map<String, List<Food>> list;
FoodList({this.status, this.list});
factory FoodList.fromJson(Map<String, dynamic> json) {
var list = json['list'] as Map;
var foodList = list.map((key, value) {
return MapEntry(key, (value as List).map((e) => Food.fromJson(e)).toList());
});
return FoodList(status: json['status'], list: foodList);
}
}
class Food {
String id;
String title;
String price;
String image;
String v;
Food({this.id, this.title, this.price, this.image, this.v});
factory Food.fromJson(Map<String, dynamic> json) {
return Food(
id: json['id'],
title: json['t'],
price: json['p'],
image: json['i'],
v: json['v']);
}
}

How do I get a list of column data from an array into a list in flutter (dart)

I've been trying to get a column from a array into a list, I'm can't seem to figure how to do it, and I couldn't find a solution online. Most of the array i find only aren't nested.
{
"status": true,
"data": {
"1": [
{
"id": "1",
"name": "500MB [SME]",
"price": "220",
"telco_price": "0"
},
{
"id": "2",
"name": "1GB [SME]",
"price": "410",
"telco_price": "0"
},
{
"id": "3",
"name": "2GB [SME]",
"price": "800",
"telco_price": "0"
},
],
"2": [
{
"id": "AIR1000",
"name": "1.5GB ",
"price": "920",
"telco_price": "920"
},
{
"id": "AIR2000",
"name": "4.5GB",
"price": "1840",
"telco_price": "1840"
},
{
"id": "AIR2500",
"name": "6GB",
"price": "2300",
"telco_price": "2300"
}
],
"3": [
{
"id": "9MOB500",
"name": "500MB",
"price": "400",
"telco_price": "400"
},
{
"id": "9MOB1000",
"name": "1.5GB",
"price": "850",
"telco_price": "850"
},
{
"id": "9MOB2000",
"name": "2GB",
"price": "1020",
"telco_price": "1020"
},
]
}
}
firstly, i want to get all names into a list variable which i can then populate easily on one of my page...
i want it into var nameList = []; where its' stated "1" then the next into another variable like that
Do on fetch like
import 'package:http/http.dart' as http;
....
List<DataClass> nameList = [];
fetch() async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
MyResponse myResponse = MyResponse.fromJson(data);
final values = myResponse.data?.values;
if (values != null) {
for (final v in values) {
if(v!=null) nameList.addAll(v.toList());
}
}
}
}
Try this model class
import 'dart:convert';
class MyResponse {
final bool? status;
final Map<String, List<DataClass>?>? data;
MyResponse({
this.status,
required this.data,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if(status != null){
result.addAll({'status': status});
}
if(data != null){
result.addAll({'data': data});
}
return result;
}
factory MyResponse.fromMap(Map<String, dynamic> map) {
return MyResponse(
status: map['status'],
data: Map<String, List<DataClass>?>.from(map['data']),
);
}
String toJson() => json.encode(toMap());
factory MyResponse.fromJson(String source) => MyResponse.fromMap(json.decode(source));
}
class DataClass {
final String? id;
final String? name;
final String? price;
final String? telco_price;
DataClass({
this.id,
this.name,
this.price,
this.telco_price,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if (id != null) {
result.addAll({'id': id});
}
if (name != null) {
result.addAll({'name': name});
}
if (price != null) {
result.addAll({'price': price});
}
if (telco_price != null) {
result.addAll({'telco_price': telco_price});
}
return result;
}
factory DataClass.fromMap(Map<String, dynamic> map) {
return DataClass(
id: map['id'],
name: map['name'],
price: map['price'],
telco_price: map['telco_price'],
);
}
String toJson() => json.encode(toMap());
factory DataClass.fromJson(String source) =>
DataClass.fromMap(json.decode(source));
}

Flutter/Dart- Filter nested list

I want to filter out a list in Flutter/dart which has nested objects. I want to filter out the list based on the name property both with in the parent object and the child object subNames.
Below is the code that I have come up with, which gives me duplicates, is there a better way to solve this?
var rawData = [{
"name": "Testing 123",
"subNames": [{
"name": "Subtesting 123"
}]
},
{
"name": "Testing 456",
"subNames": [{
"name": "Subtesting 456"
}]
},
{
"name": "Testing 456",
"subNames": []
}
]
final results = [
...rawData
.where((m) =>
m.name.toLowerCase().contains('subtesting 123'))// or Testing 123
.toList(),
...rawData
.where((m) => m.subNames
.where((s) =>
s.name.toLowerCase().contains('subtesting 123')) // or Testing 123
.isNotEmpty)
.toList()
];
Expected output:
//Results
[{
"name": "Testing 123",
"subNames": [{
"name": "Subtesting 123"
}]
},
]
First of all, it's better to use Class models and typed variables over json or dynamic nested types. Using this approach we can implement our logic easier. Here is a sample:
const rawData = [
{
"name": "Testing 123",
"subNames": [
{"name": "Subtesting 123"}
]
},
{
"name": "Testing 456",
"subNames": [
{"name": "Subtesting 456"}
]
},
{"name": "Testing 456", "subNames": []}
];
class Model {
String name;
List<SubNames> subNames;
Model({this.name, this.subNames});
Model.fromJson(Map<String, dynamic> json) {
name = json['name'];
if (json['subNames'] != null) {
subNames = <SubNames>[];
json['subNames'].forEach((v) {
subNames.add(new SubNames.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
if (this.subNames != null) {
data['subNames'] = this.subNames.map((v) => v.toJson()).toList();
}
return data;
}
}
class SubNames {
String name;
SubNames({this.name});
SubNames.fromJson(Map<String, dynamic> json) {
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
return data;
}
}
void main() {
List<Model> testModelList = rawData.map((e) => Model.fromJson(e)).toList();
final result = testModelList.where((element) =>
element.name.toLowerCase().contains('subtesting 123') ||
element.subNames
.any((sub) => sub.name.toLowerCase().contains('subtesting 123')));
print('result.length : ${result.length}');
result.forEach((element) {
print(element.toJson());
});
}
You can run this sample see the result.
Try changing your results to the following
final results = [
...rawData
.where((m) =>
m.name.toLowerCase().contains('subtesting 123')
|| m.subNames
.where((s) =>
s.name.toLowerCase().contains('subtesting 123')).toList().isNotEmpty)
.toList(),
];
I'm assuming here you are parsing your rawData so you are able to use m.names instead of m['names']

How to fetch multiple data from api call and bind to a flutter widget

I will really be happy for my question to be answered. i don't really know how to display all fetched data in a widget in flutter, i am only getting a single data.
This is how my Api response looks like
{
"cartItems": [
{
"product": {
"_id": "61b0a14b4ce2a01b914ab953",
"name": "Total1",
"size": "1kg",
"price": 700,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 2,
"price": 1400,
"type": "Refil",
"_id": "61c99030eebcb51e0f2a9a37"
},
{
"product": {
"_id": "61b0a18c4ce2a01b914ab959",
"name": "Total3",
"size": "3kg",
"price": 1800,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 1,
"price": 1800,
"type": "Refil",
"_id": "61c9903feebcb51e0f2a9a3d"
},
{
"product": {
"_id": "61aa6cb89b2046e5116fabc4",
"name": "NNPC",
"size": "15kg",
"price": 17000,
"isLPG": true
},
"vendor": "61bde0f39dfb5060de241d24",
"vendorName": "NNPC NG",
"vendorLogo": "/public/o7452L7tJ-nnpc-logo.png",
"quantity": 3,
"price": 51000,
"type": "Refil",
"_id": "61c99067eebcb51e0f2a9a51"
}
]
}
This is the generated model
class GetCartItems {
List<CartItems>? cartItems;
GetCartItems({this.cartItems});
GetCartItems.fromJson(Map<String, dynamic> json) {
if (json['cartItems'] != null) {
cartItems = <CartItems>[];
json['cartItems'].forEach((v) {
cartItems!.add(new CartItems.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.cartItems != null) {
data['cartItems'] = this.cartItems!.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartItems {
Product? product;
String? vendor;
String? vendorName;
String? vendorLogo;
int? quantity;
int? price;
String? type;
String? sId;
CartItems(
{this.product,
this.vendor,
this.vendorName,
this.vendorLogo,
this.quantity,
this.price,
this.type,
this.sId});
CartItems.fromJson(Map<String, dynamic> json) {
product =
json['product'] != null ? new Product.fromJson(json['product']) : null;
vendor = json['vendor'];
vendorName = json['vendorName'];
vendorLogo = json['vendorLogo'];
quantity = json['quantity'];
price = json['price'];
type = json['type'];
sId = json['_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.product != null) {
data['product'] = this.product!.toJson();
}
data['vendor'] = this.vendor;
data['vendorName'] = this.vendorName;
data['vendorLogo'] = this.vendorLogo;
data['quantity'] = this.quantity;
data['price'] = this.price;
data['type'] = this.type;
data['_id'] = this.sId;
return data;
}
}
class Product {
String? sId;
String? name;
String? size;
int? price;
bool? isLPG;
Product({this.sId, this.name, this.size, this.price, this.isLPG});
Product.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
size = json['size'];
price = json['price'];
isLPG = json['isLPG'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['name'] = this.name;
data['size'] = this.size;
data['price'] = this.price;
data['isLPG'] = this.isLPG;
return data;
}
}
This is my controller class
class GCP extends GetxController {
var log = Logger();
FlutterSecureStorage storage = FlutterSecureStorage();
var getCartItems = GetCartItems();
#override
void onInit() {
// TODO: implement onInit
super.onInit();
getCartItems2();
}
void getCartItems2() async {
try {
String? token = await storage.read(key: "token");
String postURL = NetworkHandler().baseurl + ApiUtil.getCartItems;
Map<String, String> headers = {
"Authorization": "Bearer $token",
'Content-Type': 'application/json;charset=UTF-8',
'Charset': 'utf-8'
};
var response = await http.get(Uri.parse(postURL), headers: headers);
if (response.statusCode == 200) {
var body = jsonDecode(response.body);
getCartItems = GetCartItems.fromJson(body);
update();
} else {
print('Something went wrong');
}
} catch (ex) {
print({ex, 'An error occured, cannot get cart items'});
}
}
}
This is my view, where i am displaying just a single data
import 'package:flutter/material.dart';
import 'package:gasapp_customer/src/controllers/GetCartPostController.dart';
import 'package:get/get.dart';
class GetCart extends StatelessWidget {
final gcp = Get.put(GCP());
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child:
Text(gcp.getCartItems.cartItems![0].product!.name.toString()),
),
],
),
),
);
}
}
So my question is how can i display all the data from my response?
You can use ListView or GridView. If the widget that you will show will be same for all instances except the data provided to it, use GridView.builder.
for more info on ListView and GridView, go to:
https://api.flutter.dev/flutter/widgets/GridView-class.html
https://api.flutter.dev/flutter/widgets/ListView-class.html

How to parse this json object correctly?

As a learner, I'm trying to build my first project, however I'm facing a problem trying to parse this json object
{
"_id": 14080,
"ankamaId": 14080,
"name": "Amulette Séculaire",
"level": 200,
"type": "Amulette",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus-touch/www/game/items/200/1230.png",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/equipements/14080-amulette-seculaire",
"description": "Finalement, le secteur de la bijouterie n'a pas tellement évolué ces cent dernières années.",
"statistics": [
{
"Vitalité": {
"min": 251,
"max": 300
}
},
{
"Intelligence": {
"min": 61,
"max": 80
}
},
{
"Agilité": {
"min": 16,
"max": 25
}
},
{
"Sagesse": {
"min": 31,
"max": 40
}
},
{
"PA": {
"min": 1,
"max": null
}
},
{
"Prospection": {
"min": 16,
"max": 20
}
},
{
"Dommages Feu": {
"min": 8,
"max": 12
}
},
{
"Dommages Air": {
"min": 8,
"max": 12
}
},
{
"% Résistance Neutre": {
"min": 6,
"max": 8
}
},
{
"% Résistance Feu": {
"min": 6,
"max": 8
}
},
{
"Résistance Critiques": {
"min": 11,
"max": 15
}
}
],
}
Below is the way I'm parsing the object.
item_model.dart
#JsonSerializable(explicitToJson: true)
class Item {
int id;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Map<String, Statistic>> statistics;
Item({
this.id,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics,
});
factory Item.fromJson(Map<String,dynamic> data) => _$ItemFromJson(data);
Map<String,dynamic> toJson() => _$ItemToJson ( this);
}
#JsonSerializable()
class Statistic {
int max;
int min;
Statistic({
this.min,
this.max,
});
factory Statistic.fromJson(Map<String,dynamic> data) => _$StatisticFromJson(data);
Map<String,dynamic> toJson() => _$StatisticToJson(this);
}
item_model.g.dart
Item _$ItemFromJson(Map<String, dynamic> json) {
return Item(
id: json['id'] as int,
ankamaId: json['ankamaId'] as int,
name: json['name'] as String,
level: json['level'] as int,
type: json['type'] as String,
imgUrl: json['imgUrl'] as String,
url: json['url'] as String,
description: json['description'] as String,
statistics: (json['statistics'] as List)
?.map((e) => (e as Map<String, dynamic>)?.map(
(k, e) => MapEntry(
k,
e == null
? null
: Statistic.fromJson(e as Map<String, dynamic>)),
))
?.toList(),
);
}
Map<String, dynamic> _$ItemToJson(Item instance) => <String, dynamic>{
'id': instance.id,
'ankamaId': instance.ankamaId,
'name': instance.name,
'level': instance.level,
'type': instance.type,
'imgUrl': instance.imgUrl,
'url': instance.url,
'description': instance.description,
'statistics': instance.statistics
?.map((e) => e?.map((k, e) => MapEntry(k, e?.toJson())))
?.toList(),
};
Statistic _$StatisticFromJson(Map<String, dynamic> json) {
return Statistic(
min: json['min'] as int,
max: json['max'] as int,
);
}
Map<String, dynamic> _$StatisticToJson(Statistic instance) => <String, dynamic>{
'max': instance.max,
'min': instance.min,
};
Basically, what I want to do is show in a listview the max, and the min attribute of each element of the statistics list.
Thank you so much in advance.
Make sure the order of the model class, is same as that of the Api data. Also the data types used is compatible. Here errors can creep in. I don't see any other issues in the code
You can use this site for get your model from json, just copy and past
There's a brilliant tool (not the one that other ppl linked) that creates dart code for your JSON:
https://javiercbk.github.io/json_to_dart/
It helped me a ton when working with different APIs.
The dart code in your case would be this:
class myJson {
int iId;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Statistics> statistics;
myJson(
{this.iId,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics});
myJson.fromJson(Map<String, dynamic> json) {
iId = json['_id'];
ankamaId = json['ankamaId'];
name = json['name'];
level = json['level'];
type = json['type'];
imgUrl = json['imgUrl'];
url = json['url'];
description = json['description'];
if (json['statistics'] != null) {
statistics = new List<Statistics>();
json['statistics'].forEach((v) {
statistics.add(new Statistics.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.iId;
data['ankamaId'] = this.ankamaId;
data['name'] = this.name;
data['level'] = this.level;
data['type'] = this.type;
data['imgUrl'] = this.imgUrl;
data['url'] = this.url;
data['description'] = this.description;
if (this.statistics != null) {
data['statistics'] = this.statistics.map((v) => v.toJson()).toList();
}
return data;
}
}
class Statistics {
Vitalit vitalit;
Vitalit intelligence;
Vitalit agilit;
Vitalit sagesse;
PA pA;
Vitalit prospection;
Vitalit dommagesFeu;
Vitalit dommagesAir;
Vitalit rSistanceNeutre;
Vitalit rSistanceFeu;
Vitalit rSistanceCritiques;
Statistics(
{this.vitalit,
this.intelligence,
this.agilit,
this.sagesse,
this.pA,
this.prospection,
this.dommagesFeu,
this.dommagesAir,
this.rSistanceNeutre,
this.rSistanceFeu,
this.rSistanceCritiques});
Statistics.fromJson(Map<String, dynamic> json) {
vitalit = json['Vitalité'] != null
? new Vitalit.fromJson(json['Vitalité'])
: null;
intelligence = json['Intelligence'] != null
? new Vitalit.fromJson(json['Intelligence'])
: null;
agilit =
json['Agilité'] != null ? new Vitalit.fromJson(json['Agilité']) : null;
sagesse =
json['Sagesse'] != null ? new Vitalit.fromJson(json['Sagesse']) : null;
pA = json['PA'] != null ? new PA.fromJson(json['PA']) : null;
prospection = json['Prospection'] != null
? new Vitalit.fromJson(json['Prospection'])
: null;
dommagesFeu = json['Dommages Feu'] != null
? new Vitalit.fromJson(json['Dommages Feu'])
: null;
dommagesAir = json['Dommages Air'] != null
? new Vitalit.fromJson(json['Dommages Air'])
: null;
rSistanceNeutre = json['% Résistance Neutre'] != null
? new Vitalit.fromJson(json['% Résistance Neutre'])
: null;
rSistanceFeu = json['% Résistance Feu'] != null
? new Vitalit.fromJson(json['% Résistance Feu'])
: null;
rSistanceCritiques = json['Résistance Critiques'] != null
? new Vitalit.fromJson(json['Résistance Critiques'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.vitalit != null) {
data['Vitalité'] = this.vitalit.toJson();
}
if (this.intelligence != null) {
data['Intelligence'] = this.intelligence.toJson();
}
if (this.agilit != null) {
data['Agilité'] = this.agilit.toJson();
}
if (this.sagesse != null) {
data['Sagesse'] = this.sagesse.toJson();
}
if (this.pA != null) {
data['PA'] = this.pA.toJson();
}
if (this.prospection != null) {
data['Prospection'] = this.prospection.toJson();
}
if (this.dommagesFeu != null) {
data['Dommages Feu'] = this.dommagesFeu.toJson();
}
if (this.dommagesAir != null) {
data['Dommages Air'] = this.dommagesAir.toJson();
}
if (this.rSistanceNeutre != null) {
data['% Résistance Neutre'] = this.rSistanceNeutre.toJson();
}
if (this.rSistanceFeu != null) {
data['% Résistance Feu'] = this.rSistanceFeu.toJson();
}
if (this.rSistanceCritiques != null) {
data['Résistance Critiques'] = this.rSistanceCritiques.toJson();
}
return data;
}
}
class Vitalit {
int min;
int max;
Vitalit({this.min, this.max});
Vitalit.fromJson(Map<String, dynamic> json) {
min = json['min'];
max = json['max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['min'] = this.min;
data['max'] = this.max;
return data;
}
}
class PA {
int min;
Null max;
PA({this.min, this.max});
PA.fromJson(Map<String, dynamic> json) {
min = json['min'];
max = json['max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['min'] = this.min;
data['max'] = this.max;
return data;
}
}
You can use this tool which you just provide it with the JSON message and it will give you a class with all the variables and two function by which can parse the JSON message to the object or vice versa.
Steps:
insert a JSON message to the tool and give the class a name (don't forget to choose dart as the language)
create a new dart file and paste the class from the tool (let's assume the class name is Item)
Call final item = itemFromJson(jsonString); for parsing the JSON to the new object
Which then you can access the variables by via e.g. item.id
Edit:
so for your code, it will be:
item_model.dart
// To parse this JSON data, do
//
// final item = itemFromJson(jsonString);
import 'dart:convert';
Item itemFromJson(String str) => Item.fromJson(json.decode(str));
String itemToJson(Item data) => json.encode(data.toJson());
class Item {
Item({
this.id,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics,
});
int id;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Map<String, Statistic>> statistics;
factory Item.fromJson(Map<String, dynamic> json) => Item(
id: json["_id"],
ankamaId: json["ankamaId"],
name: json["name"],
level: json["level"],
type: json["type"],
imgUrl: json["imgUrl"],
url: json["url"],
description: json["description"],
statistics: List<Map<String, Statistic>>.from(json["statistics"].map((x) => Map.from(x).map((k, v) => MapEntry<String, Statistic>(k, Statistic.fromJson(v))))),
);
Map<String, dynamic> toJson() => {
"_id": id,
"ankamaId": ankamaId,
"name": name,
"level": level,
"type": type,
"imgUrl": imgUrl,
"url": url,
"description": description,
"statistics": List<dynamic>.from(statistics.map((x) => Map.from(x).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())))),
};
}
class Statistic {
Statistic({
this.min,
this.max,
});
int min;
int max;
factory Statistic.fromJson(Map<String, dynamic> json) => Statistic(
min: json["min"],
max: json["max"] == null ? null : json["max"],
);
Map<String, dynamic> toJson() => {
"min": min,
"max": max == null ? null : max,
};
}
You can access the variables via:
void main(){
String jsonString = "{\"_id\":14080,\"ankamaId\":14080,\"name\":\"Amulette S\u00e9culaire\",\"level\":200,\"type\":\"Amulette\",\"imgUrl\":\"https:\/\/s.ankama.com\/www\/static.ankama.com\/dofus-touch\/www\/game\/items\/200\/1230.png\",\"url\":\"https:\/\/www.dofus-touch.com\/fr\/mmorpg\/encyclopedie\/equipements\/14080-amulette-seculaire\",\"description\":\"Finalement, le secteur de la bijouterie n'a pas tellement \u00e9volu\u00e9 ces cent derni\u00e8res ann\u00e9es.\",\"statistics\":[{\"Vitalit\u00e9\":{\"min\":251,\"max\":300}},{\"Intelligence\":{\"min\":61,\"max\":80}},{\"Agilit\u00e9\":{\"min\":16,\"max\":25}},{\"Sagesse\":{\"min\":31,\"max\":40}},{\"PA\":{\"min\":1,\"max\":null}},{\"Prospection\":{\"min\":16,\"max\":20}},{\"Dommages Feu\":{\"min\":8,\"max\":12}},{\"Dommages Air\":{\"min\":8,\"max\":12}},{\"% R\u00e9sistance Neutre\":{\"min\":6,\"max\":8}},{\"% R\u00e9sistance Feu\":{\"min\":6,\"max\":8}},{\"R\u00e9sistance Critiques\":{\"min\":11,\"max\":15}}]}";
final device = deviceFromJson(jsonString);
print(device.id);
}