Convert object to array in flutter - flutter

I need to convert object to array in flutter , Kindly find the json
{
"billing": [
{
"id": 1,
"add_id": 23
}
],
"shipping": [
{
"id": 2,
"add_id": 345
},
{
"id": 3,
"add_id": 345
}
]
}
I need to convert into array and map to model in flutter , how to do it

Use the following code to convert your JSON to a class object, the fromJson function convert JSON to object, and the toJson function convert the object to json.
class YourClassName {
List<Billing> billing;
List<Shipping> shipping;
YourClassName({this.billing, this.shipping});
YourClassName.fromJson(Map<String, dynamic> json) {
if (json['billing'] != null) {
billing = new List<Billing>();
json['billing'].forEach((v) {
billing.add(new Billing.fromJson(v));
});
}
if (json['shipping'] != null) {
shipping = new List<Shipping>();
json['shipping'].forEach((v) {
shipping.add(new Shipping.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.billing != null) {
data['billing'] = this.billing.map((v) => v.toJson()).toList();
}
if (this.shipping != null) {
data['shipping'] = this.shipping.map((v) => v.toJson()).toList();
}
return data;
}
}
class Billing {
int id;
int addId;
Billing({this.id, this.addId});
Billing.fromJson(Map<String, dynamic> json) {
id = json['id'];
addId = json['add_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['add_id'] = this.addId;
return data;
}
}
class Shipping {
int id;
int addId;
Shipping({this.id, this.addId});
Shipping.fromJson(Map<String, dynamic> json) {
id = json['id'];
addId = json['add_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['add_id'] = this.addId;
return data;
}
}

Related

How to deserialize a JSON where some keys are duplicated

The json response looks like this:
{
"name": "A name",
"international": {
"name": {
"en": "A name",
"fr": "Un nom"
}
}
}
I tried the following code to deserialize it:
import 'package:json_annotation/json_annotation.dart';
import 'dart:convert';
part 'model.g.dart';
void main() {
var json = '''{
"name": "A name",
"international": {
"name": {
"en": "A name",
"fr": "Un nom"
}
}
}''';
var model = Model.fromJson(jsonDecode(json));
}
#JsonSerializable()
class Model {
Model({
required this.name,
required this.internationalNames,
});
factory Model.fromJson(Map<String, dynamic> json) => _$ModelFromJson(json);
final String name;
#JsonKey(readValue: _readInternational, name: "name")
final Map<String, String> internationalNames;
static Object? _readInternational(Map<dynamic, dynamic> json, String key) =>
json['international'][key];
}
I am getting an error when running the build_runner:
More than one field has the JSON key for name "name"
even though the internationalNames one is nested inside the international object, so there is no duplicate keys. What could I do to deserialize this?
I get it to work by creating a InternationalModel class:
import 'package:json_annotation/json_annotation.dart';
import 'dart:convert';
part 'temp.g.dart';
void main() {
var json = '''{
"name": "A name",
"international": {
"name": {
"en": "A name",
"fr": "Un nom"
}
}
}''';
var model = Model.fromJson(jsonDecode(json));
}
#JsonSerializable()
class Model {
Model({
required this.name,
required this.international,
});
factory Model.fromJson(Map<String, dynamic> json) => _$ModelFromJson(json);
final String name;
final InternationalModel international;
}
#JsonSerializable()
class InternationalModel {
InternationalModel({
required this.names,
});
factory InternationalModel.fromJson(Map<String, dynamic> json) =>
_$InternationalModelFromJson(json);
#JsonKey(name: 'name')
final Map<String, String> names;
}
Thanks to Nagual for pointing me towards this solution.
I am able to decode it using below code.
import 'dart:convert';
void main() {
var json = '''{
"name": "A name",
"international": {
"name": {
"en": "A name",
"fr": "Un nom"
}
}
}''';
Model model = Model.fromJson(jsonDecode(json));
print(model.international!.name!.en);
}
class Model {
String? name;
International? international;
Model({this.name, this.international});
Model.fromJson(Map<String, dynamic> json) {
name = json['name'];
international = json['international'] != null
? new International.fromJson(json['international'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
if (this.international != null) {
data['international'] = this.international!.toJson();
}
return data;
}
}
class International {
Name? name;
International({this.name});
International.fromJson(Map<String, dynamic> json) {
name = json['name'] != null ? new Name.fromJson(json['name']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.name != null) {
data['name'] = this.name!.toJson();
}
return data;
}
}
class Name {
String? en;
String? fr;
Name({this.en, this.fr});
Name.fromJson(Map<String, dynamic> json) {
en = json['en'];
fr = json['fr'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['en'] = this.en;
data['fr'] = this.fr;
return data;
}
}

Serializing JSON response in Flutter

I would need assistance in serializing the below JSON Response. By far, I've managed to only extract the district property but cannot seem to understand how to go about with the properties of ward_no. The code for what I've done is below. Please note that I would like to serialize the JSON response in the same approach as on my code as I found it nearly impossible to wrap my head around the Serializing techniques suggested in the Official Documents.
The Response:
[
{
"district": "Kolkata", //I've only managed to extract this.
"ward_no": [
{
"ward": "6",
"grievance": [
{
"serial_number": "0001",
"name": "Siddhartha Chatterjee"
},
{
"serial_number": "0002",
"name": "Sajujjo Ghosh"
}
],
"general": [
{
"serial_number": "0003",
"name": "Dr. Partha Pratim Paul"
},
{
"serial_number": "0004",
"name": "Dr. Partha Pratim Paul"
}
],
"urgent": [
{
"serial_number": "0005",
"name": "Ritwick Banerjee"
},
{
"serial_number": "0006",
"name": "Soumadip Banerjee"
}
],
"services": [
{
"serial_number": "0007",
"name": "Tanajeet Biswas"
},
{
"serial_number": "0008",
"name": "Durba Chatterjee"
}
]
}
]
}
]
The code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Model {
final String district;
Model({required this.district});
}
class ModelClass with ChangeNotifier {
List<dynamic> _data = [];
List<dynamic> get data {
return [..._data];
}
Future<void> getData() async {
final url = Uri.http('192.168.0.6:3007', '/fetchData');
final response = await http.get(url);
print(response);
final extractedData = json.decode(response.body);
print(extractedData);
Map<String, Model> temp = {};
extractedData.forEach((value) {
temp.putIfAbsent(
value['_id'],
() =>
Model(district: value['district']));
});
print(temp);
_data = temp.values.toList();
print(_data);
}
}
P.S: I'm not looking to use boilerplate code generated by those JSON to Dart converter links
You can use this tools which will generate data class form the provided json
https://jsontodart.zariman.dev/
class Response {
String? district;
List<WardNo>? wardNo;
Response({this.district, this.wardNo});
Response.fromJson(Map<String, dynamic> json) {
this.district = json["district"];
this.wardNo = json["ward_no"]==null ? null : (json["ward_no"] as List).map((e)=>WardNo.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["district"] = this.district;
if(this.wardNo != null)
data["ward_no"] = this.wardNo?.map((e)=>e.toJson()).toList();
return data;
}
}
class WardNo {
String? ward;
List<Grievance>? grievance;
List<General>? general;
List<Urgent>? urgent;
List<Services>? services;
WardNo({this.ward, this.grievance, this.general, this.urgent, this.services});
WardNo.fromJson(Map<String, dynamic> json) {
this.ward = json["ward"];
this.grievance = json["grievance"]==null ? null : (json["grievance"] as List).map((e)=>Grievance.fromJson(e)).toList();
this.general = json["general"]==null ? null : (json["general"] as List).map((e)=>General.fromJson(e)).toList();
this.urgent = json["urgent"]==null ? null : (json["urgent"] as List).map((e)=>Urgent.fromJson(e)).toList();
this.services = json["services"]==null ? null : (json["services"] as List).map((e)=>Services.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["ward"] = this.ward;
if(this.grievance != null)
data["grievance"] = this.grievance?.map((e)=>e.toJson()).toList();
if(this.general != null)
data["general"] = this.general?.map((e)=>e.toJson()).toList();
if(this.urgent != null)
data["urgent"] = this.urgent?.map((e)=>e.toJson()).toList();
if(this.services != null)
data["services"] = this.services?.map((e)=>e.toJson()).toList();
return data;
}
}
class Services {
String? serialNumber;
String? name;
Services({this.serialNumber, this.name});
Services.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}
class Urgent {
String? serialNumber;
String? name;
Urgent({this.serialNumber, this.name});
Urgent.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}
class General {
String? serialNumber;
String? name;
General({this.serialNumber, this.name});
General.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}
class Grievance {
String? serialNumber;
String? name;
Grievance({this.serialNumber, this.name});
Grievance.fromJson(Map<String, dynamic> json) {
this.serialNumber = json["serial_number"];
this.name = json["name"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["serial_number"] = this.serialNumber;
data["name"] = this.name;
return data;
}
}

List array of array in class model flutter

How to create class model in flutter if List Array of Array have 2 type data
Example
"value" : [["Water Melon", "Apple", 10, 23]]
#JsonSerializable()
class GetReportBodyData {
String type;
String title;
List<String> headers;
List<List<int>> value = new List<List<int>>();
GetReportBodyData({this.type, this.title, this.headers, this.value});
#override
String toString() {
return 'GetReportBodyData{type: $type, title: $title, header: $headers, value: $value}';
}
factory GetReportBodyData.fromJson(Map<String, dynamic> json) {
return GetReportBodyData(
type: json["type"],
title: json["title"],
headers: json["header"] != null ? List<String>.from(json["header"]) :[],
value: List<List<int>>.from(json["value"])
);
}
Map<String, dynamic>toJson() => {
"type": type,
"title": title,
"header": headers,
"value": value
};
}
class example {
List<List> value;
example({this.value});
example.fromJson(Map<String, dynamic> json) {
if (json['value'] != null) {
value = new List<List>();
json['value'].forEach((v) { value.add(new List.fromJson(v)); });
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.value != null) {
data['value'] = this.value.map((v) => v.toJson()).toList();
}
return data;
}
}
class Value {
Value({});
Value.fromJson(Map<String, dynamic> json) {
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
return data;
}

I am getting The method 'cast' was called on null while parsing json

I have following json in my API response :
{
"data": [{
"orderid": "123",
"item_names": [
"item1",
"item2",
"item3",
"item4"
]
}]
}
and i have following model class in dart :
class OrderListResponse {
List<OrderListItemModel> data;
OrderListResponse({this.data});
OrderListResponse.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<OrderListItemModel>();
json['data'].forEach((v) {
data.add(new OrderListItemModel.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class OrderListItemModel {
String id;
List<String> items;
OrderListItemModel({this.id,
this.items,
});
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
items = json['item_names'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['item_names'] = this.items;
return data;
}
}
When I will get data in API it gives me an error The method 'cast' was called on null. I am not getting why it throws this error. Any solution for this ?
I recommend you to use this website to convert your jsons
and so on, to fix you're code you need to change
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
items = json['item_names'].cast<String>();
}
to this
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['orderid'];
items = json["item_names"] == null? [] : List<String>.from(json["item_names"].map((x) => x))
}
You had a few mistakes in your code:
You are trying to cast a string to an array.
Your are trying to parse field id but the JSON field is orderid
Try this code:
import 'dart:convert';
void main() {
var js = '''{
"data": [{
"orderid": "123",
"item_names": [
"item1",
"item2",
"item3",
"item4"
]
}]
}''';
var orders = OrderListResponse.fromJson(json.decode(js));
for (var order in orders.data) {
print(order.id);
for (var item in order.items) {
print(item);
}
}
}
class OrderListResponse {
List<OrderListItemModel> data;
OrderListResponse({this.data});
OrderListResponse.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<OrderListItemModel>();
json['data'].forEach((v) {
data.add(new OrderListItemModel.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class OrderListItemModel {
String id;
List<String> items;
OrderListItemModel({this.id,
this.items,
});
OrderListItemModel.fromJson(Map<String, dynamic> json) {
id = json['orderid'];
items = List<String>.from(json["item_names"].map((x) => x));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['orderid'] = this.id;
data['item_names'] = this.items;
return data;
}
}

'List<dynamic>' is not a subtype of type 'List<options>'

I am getting error as 'List<dynamic>' is not a subtype of type 'List<options>'
Here is my code:
List<SampleModel> cartList = allStores.keys
// var allStores = response.data['data'];
// var cartList = allStores.keys
.map((name) => SampleModel(
sname: name,
selected: false,
storeList: allStores[name].map((name) => SampleModel(
sname: name,
selected: false,
storeList: allStores[name].map<Store>((store) => Store(
id: store['id'],
selected: false,
stid: store['stid'],
product: Products(
id: store['product']['id'],
type: store['product']['type_id'],
options: store['product']['options'].length > 0 ? store['product']['options'].map((f) => Options.fromJson(f)).toList() : null
),
)
).toList(),
)
).toList();
Model:
class SampleModel {
String sname;
bool selected;
List<Store> storeList;
SampleModel({this.sname, this.selected, this.storeList});
SampleModel.fromJson(Map<String, dynamic> json) {
sname = json['sname'];
selected = json['selected'];
storeList = List<Store>.from(json["storeList"].map((x) => Store.fromJson(x)));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sname'] = this.sname;
data['selected'] = this.selected;
data['storeList'] = List<dynamic>.from(storeList.map((x) => x.toJson()));
return data;
}
}
class Store {
int id;
int stid;
Store({
this.id,
this.stid,
});
Store.fromJson(Map<String, dynamic> json) {
id = json['id'];
stid = json['cart_id'];
selected = json['selected'];
quantity = json['quantity'];
product = Products.fromJson(json["product"]);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['cart_id'] = this.stid;
data['product'] = product.toJson();
return data;
}
}
class Products {
int id;
String name;
List<Options> options;
Products({
this.id,
this.name,
this.options,
});
Products.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
type = json['type'];
options = json["options"] == null
? null
: List<Options>.from(
json["options"].map((x) => Options.fromJson(x)));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['options'] = options == null
? null
: List<dynamic>.from(options.map((x) => x.toJson()));
return data;
}
}
}
class Options {
int id;
String name;
Options({
this.id,
this.name,
});
Options.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Here is my sample json
{
"sta1": [{
"id": 948,
"sid": 67,
"product": {
"id": 123,
"name": "tesssss",
"Options": [{
"id": 1,
"name": "asdasd"
}, {
"id": 2,
"name": "wer",
"seq": 1
}]
}
}],
"sta2": [{
"id": 948,
"sid": 67,
"product": {
"id": 123,
"name": "tesssss",
"Options": [{
"id": 1,
"name": "asdasd"
}, {
"id": 2,
"name": "wer",
"seq": 1
}]
}
}]
}
Everything works fine but options is not mapping, it shows error as
'List' is not a subtype of type 'List'
What am I missing here? Its an object and options is an array so I need to have it as a list in front end
everything i can able to loop but one thing options is not working
getting error in following line
options: store['product']['options'].length > 0 ? store['product']['options'].map((f) => Options.fromJson(f)).toList() : null
I had a similar problem, I think that Flutter lost the reference of type of object, but I can fix using like this in your fromJson:
options = json["options"] == null
? null
: List<Options>.from(
json["options"].map<Option>((x) => Options.fromJson(x.cast<String, dynamic>())));
}
Casting the map and using the cast in your map object.
I hope that can help you too.