I have a JSON like this. Because the Crew is different from others, I don't know how to write its model. like factory xxxx.fromJson Thanks
[
{
"Employee": [
"Employee A",
"Employee B",
"Employee C",
]
},
{
"Equipment": [
"Equipment 1",
"Equipment 2",
"Equipment 3",
]
},
{
"Task": ["Task a", "Task b", "Task c"]
},
{
"Crew": [
{
"crew_name": "Crew One",
"employee": ["Employee3"],
"equipment": ["Equipment2"]
},
{
"crew_name": "Crew Two",
"employee": ["Employee1", "Employee2"],
"equipment": ["Equipment1"]
},
],
},
]
You can use this approach.
import 'dart:convert';
class Crew {
Crew({
this.crewName,
this.employee,
this.equipment,
});
String crewName;
List<String> employee;
List<String> equipment;
factory Crew.fromMap(Map<String, dynamic> json) => Crew(
crewName: json["crew_name"],
employee: List<String>.from(json["employee"].map((x) => x)),
equipment: List<String>.from(json["equipment"].map((x) => x)),
);
Map<String, dynamic> toMap() => {
"crew_name": crewName,
"employee": List<dynamic>.from(employee.map((x) => x)),
"equipment": List<dynamic>.from(equipment.map((x) => x)),
};
}
class CrewList {
CrewList({
this.crew,
});
List<Crew> crew;
factory CrewList.fromMap(Map<String, dynamic> json) => CrewList(
crew: List<Crew>.from(json["Crew"].map((x) => Crew.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"Crew": List<dynamic>.from(crew.map((x) => x.toMap())),
};
}
CrewList crewListFromMap(String str) => CrewList.fromMap(json.decode(str));
String crewListToMap(CrewList data) => json.encode(data.toMap());
void main(){
String str = "{\"Crew\":[{\"crew_name\":\"Crew One\",\"employee\":[\"Employee3\"],\"equipment\":[\"Equipment2\"]},{\"crew_name\":\"Crew Two\",\"employee\":[\"Employee1\",\"Employee2\"],\"equipment\":[\"Equipment1\"]}]}";
CrewList crewList = crewListFromMap(str);
print(crewListToMap(crewList));
}
Check this website Quicktype.
Just copy and paste your json and get models on any language.
But remember this is quick and lazy way of doing it. I'd recommend you read documentation to learn how to design models
Related
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']
I want to convert the a List<Object> to a List<List<dynamic>> and send it as JSON to an API.
Here is my Object model class CartMapModel:
class CartMapModel {
String itemName;
String itemPrice;
String itemDescription;
CartMapModel({this.itemDescription,this.itemPrice,this.itemName});
Map<String, dynamic> toJson() {
return {
"itemName": itemName,
"itemPrice": itemPrice,
"itemDescription" : itemDescription
};
}
}
Here is my List<CartMapModel>:
cartOrderList.add(
CartMapModel(
itemPrice: itmPrice.toString(),
itemName: itmName,
itemDescription: itmDesc,
)
);
I want to convert it to a List<List<dynamic>>:
[
[
"Item Name 1",
"123",
"Item 1 Description"
],
[
"Item Name 2",
"456",
"Item 2 Description"
],
[
"Item Name 3",
"789",
"Item 3 Description"
]
]
Is this what you are looking for?
List<Map<String, dynamic>> jsonDataList =
cartOrderList.map((cartOrder) => cartOrder.toJson().values.toList()).toList();
I am getting a response as key as numeric. How to map data for the following response
{
"1": [
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
],
"2": [
{
"id": 9,
"name": "ttt1"
},
{
"id": 5,
"name": "ttt3"
}
],
"3": [
{
"id": 4,
"name": "ttg",
"status_id": 1
}
]
}
Here is my model
import 'dart:convert';
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
String homeBannerModelToJson(Map<String, List<HomeBannerModel>> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, List<dynamic>.from(v.map((x) => x.toJson())))));
class HomeBannerModel {
int id;
String name;
HomeBannerModel({this.id, this.name});
HomeBannerModel.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;
}
}
I need to take the value in UI as
var data1 = data['1'];
var data2= data['2'];
var data3= data['3'];
but I am getting errors. help how to get the data of each key in each of the variable
but while mapping I am getting errors I have added part of my code in UI
_message:"type 'Map<String, dynamic>' is not a subtype of type 'List'"
The following method will convert your json string to a valid map object so that you can get your data the way you wanted.
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
to access data
final data = homeBannerModelFromJson(your_json_string);
print(data['1'][0].name); // test 1
You current json structure is Map<String, List<Map<String, dynamic>>>
You can try something like
var json = {...};
json.forEach((key, list) {
list.forEach((homeBannerModelMap) {
HomeBannerModel hBM = HomeBannerModel.fromJson(homeBannerModelMap);
});
});
You getting the error because your data is the type of Map, not the List.
So you can do something like this:
// [data] is result banners
List data = [];
// [result] is your object variable {"1": [{"id": 1, "name": "Welcome!"}]} etc
// So .forEach method is used for iterating through your json object
result.forEach((k, v){
// in which iteration I will map every instance to List of [HomeBannerModel]
var value = v.map((banner) => HomeBannerModel.fromJson(banner)).toList();
//in result I will add the result to our [banners] List
data.add(value);
});
But in this case, you should do:
data1 = data[1] // use int as the key, result will be List of BannerModels [Instance of 'HomeBannerModel', Instance of 'HomeBannerModel']
instead of:
var data1 = data['1']; //use string as the key
Please try the following code with just one model 'HomeBannerModel'.
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final Map datas = {};
json.forEach((key, value) {
datas.addAll(
{"$key": value.map((ele) => HomeBannerModel.fromMap(ele)).toList()});
});
print(datas["1"]);
print(datas["2"]);
print(datas["3"]);
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
You may also try with two models (1) Data and (2) HomeBannerModel. Please see the following code :
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final List<Data> data = [];
json.forEach((key, value) {
data.add(Data.fromMap({"id": key, "details": value}));
});
print(data.firstWhere((e) => e.dataID == '1').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '2').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '3').homeBannerModel);
}
class Data {
final String dataID;
final List<HomeBannerModel> homeBannerModel;
Data({
this.dataID,
this.homeBannerModel,
});
factory Data.fromMap(Map<String, dynamic> map) {
if (map == null) return null;
return Data(
dataID: map["id"],
homeBannerModel: (map["details"]
.map<HomeBannerModel>((ele) => HomeBannerModel.fromMap(ele))
.toList() as List<HomeBannerModel>));
}
#override
String toString() => 'Data(id: $dataID, details: $homeBannerModel)';
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
From what I’m seeing in the sample response you shared , the kets are all string as should be... "1" is also String FYI.
Coming to the error you're getting its because you are probably using the var data1,data2,data3 as a map which it isn't.
var data1 = data['1'];
if you print this var you will get :
[
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
]
If you want to access the submap with id of 6 and name Test 1 do the following:
print(data1[0]);
to display name:
print(data1[0]["name"]);
my json=
{
"result": {
"name": "json1",
"pages": [{
"zones": [{
"title": "title1"
},
{
"title": "title2"
}],
"id": 4
},
{
"zones": [{
"title": "title3"
},
{
"title": "title4"
}],
"id": 12
}],
"creatorUserName": "admin",
"id": 2
}
}
futurebuilder code
List post = snapshot.data["result"]["pages"];
return new Stack(
children: post.where((val) => val["id"] == 4).map((post) {
for (var item in post['zones']) {
print("title "+ item['title']);
Container(
child: Text(item["title"]),
); //Container
}
}).toList(),
); //Stack
Error code: Stack's children must not contain any null values, but a null value was found at index 0
enter image description here
help how can to build an algorithms
if get id = 4 zones -> Text(title1), Text(title2),
else id empty zones -> Text(title1), Text(title2), zones -> Text(title3), Text(title4),
Try
List post = snapshots.data["result"]["pages"];
First Make a model class for your JSON response using this amazing webpage, after that you can easily. call the needed data
import 'dart:convert';
YourModelClassName yourModelClassNameFromJson(String str) => YourModelClassName.fromJson(json.decode(str));
String yourModelClassNameToJson(YourModelClassName data) => json.encode(data.toJson());
class YourModelClassName {
Result result;
YourModelClassName({
this.result,
});
factory YourModelClassName.fromJson(Map<String, dynamic> json) => YourModelClassName(
result: Result.fromJson(json["result"]),
);
Map<String, dynamic> toJson() => {
"result": result.toJson(),
};
}
class Result {
String name;
List<Page> pages;
String creatorUserName;
int id;
Result({
this.name,
this.pages,
this.creatorUserName,
this.id,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
name: json["name"],
pages: List<Page>.from(json["pages"].map((x) => Page.fromJson(x))),
creatorUserName: json["creatorUserName"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"name": name,
"pages": List<dynamic>.from(pages.map((x) => x.toJson())),
"creatorUserName": creatorUserName,
"id": id,
};
}
class Page {
List<Zone> zones;
int id;
Page({
this.zones,
this.id,
});
factory Page.fromJson(Map<String, dynamic> json) => Page(
zones: List<Zone>.from(json["zones"].map((x) => Zone.fromJson(x))),
id: json["id"],
);
Map<String, dynamic> toJson() => {
"zones": List<dynamic>.from(zones.map((x) => x.toJson())),
"id": id,
};
}
class Zone {
String title;
Zone({
this.title,
});
factory Zone.fromJson(Map<String, dynamic> json) => Zone(
title: json["title"],
);
Map<String, dynamic> toJson() => {
"title": title,
};
}
The error says it cannot create ApplicableFlight there is a problem onFlightSegmentReference List dynamic is not a subtype of type 'Map String, dynamic
This is where json.decode and fromJson are used
var map = json.decode(response.body) as Map<String, dynamic>;
ResponseGate responseGate = new ResponseGate.fromJson(map);
this is the snip of the output from json.decode
..,ApplicableFlight: {FlightReferences: F1,FlightSegmentReference: {ref: 0199,ClassOfService: {refs:ABCD,Code: {SeatsLeft: 6,content: Z},MarketingName:world}},OriginDestinationReferences:FF},
response.body look like bellow:
{ ..,
{
"ApplicableFlight": {
"FlightReferences": "F1",
"FlightSegmentReference": {
"ref": "0199",
"ClassOfService": {
"refs": "FBCODE1ADT",
"Code": {
"SeatsLeft": 7,
"content": "Z"
},
"MarketingName": "world"
}
},
"OriginDestinationReferences": "FF"
}
},}
This is where the objects are defined and ResponseGate.fromJson(map) looking for
x.dart
#JsonSerializable()
class ResponseGate {
#JsonKey(name: "Offer")
List<Offer> offer;
ResponseGate(this.offer);
factory ResponseGate.fromJson(Map<String, dynamic> json) =>
_$ResponseGateFromJson(json);
}
#JsonSerializable()
class Offer {
#JsonKey(name: "PricedOffer")
PricedOffer pricedOffer;
Offer(this.pricedOffer);
factory Offer.fromJson(Map<String, dynamic> json) =>
_$OfferFromJson(json);
}
#JsonSerializable()
class PricedOffer {
#JsonKey(name: "Associations")
List<Associates> listOfAssociations;
PricedOffer(this.listOfAssociations);
factory PricedOffer.fromJson(Map<String, dynamic> json) =>
_$PricedOfferFromJson(json);
}
#JsonSerializable()
class Associates {
#JsonKey(name: "ApplicableFlight")
ApplicableFlight applicableFlight;
Associates(this.applicableFlight);
factory Associates.fromJson(Map<String, dynamic> json) =>
_$AssociatesFromJson(json);
}
#JsonSerializable()
class ApplicableFlight {
#JsonKey(name: "FlightReferences")
var flightReference;
#JsonKey(name: "FlightSegmentReference")
FlightSegmentReference flightSegmentReference;
#JsonKey(name: "OriginDestinationReferences")
var originDestinationReferences;
ApplicableFlight(this.flightReference, this.flightSegmentReference,
this.originDestinationReferences);
factory ApplicableFlight.fromJson(Map<String, dynamic> json) =>
_$ApplicableFlightFromJson(json);
}
#JsonSerializable()
class FlightSegmentReference {
#JsonKey(name: "ref")
var ref;
#JsonKey(name: "ClassOfService")
ClassOfService classOfService;
FlightSegmentReference(this.ref, this.classOfService);
factory FlightSegmentReference.fromJson(Map<String, dynamic> json) =>
_$FlightSegmentReferenceFromJson(json);
}
#JsonSerializable()
class ClassOfService {
#JsonKey(name: "refs")
var refs;
#JsonKey(name: "Code")
Code code;
#JsonKey(name: "MarketingName")
var marketingName;
ClassOfService(this.refs, this.code, this.marketingName);
factory ClassOfService.fromJson(Map<String, dynamic> json) =>
_$ClassOfServiceFromJson(json);
}
#JsonSerializable()
class Code {
#JsonKey(name: "SeatsLeft")
var seatLeft;
#JsonKey(name: "content")
var content;
Code(this.seatLeft, this.content);
factory Code.fromJson(Map<String, dynamic> json) => _$CodeFromJson(json);
}
x.g.dart
ApplicableFlight _$ApplicableFlightFromJson(Map<String, dynamic> json)
{
return $checkedNew('ApplicableFlight', json, () {
$checkKeys(json, allowedKeys: const [
'FlightReferences',
'FlightSegmentReference',
'OriginDestinationReferences'
]);
final val = ApplicableFlight(
$checkedConvert(json, 'FlightReferences', (v) => v),
$checkedConvert(
json,
'FlightSegmentReference',
(v) => v == null
? null
: FlightSegmentReference.fromJson(v as Map<String, dynamic>)),
$checkedConvert(json, 'OriginDestinationReferences', (v) => v));
return val;
}, fieldKeyMap: const {
'flightReference': 'FlightReferences',
'flightSegmentReference': 'FlightSegmentReference',
'originDestinationReferences': 'OriginDestinationReferences'
});
}
FlightSegmentReference _$FlightSegmentReferenceFromJson(
Map<String, dynamic> json) {
return $checkedNew('FlightSegmentReference', json, () {
$checkKeys(json, allowedKeys: const ['ref', 'ClassOfService']);
final val = FlightSegmentReference(
$checkedConvert(json, 'ref', (v) => v),
$checkedConvert(
json,
'ClassOfService',
(v) => v == null
? null
: ClassOfService.fromJson(v as Map<String, dynamic>)));
return val;
}, fieldKeyMap: const {'classOfService': 'ClassOfService'});
}
ClassOfService _$ClassOfServiceFromJson(Map<String, dynamic> json) {
return $checkedNew('ClassOfService', json, () {
$checkKeys(json, allowedKeys: const ['refs', 'Code', 'MarketingName']);
final val = ClassOfService(
$checkedConvert(json, 'refs', (v) => v),
$checkedConvert(json, 'Code',
(v) => v == null ? null : Code.fromJson(v as Map<String, dynamic>)),
$checkedConvert(json, 'MarketingName', (v) => v));
return val;
}, fieldKeyMap: const {'code': 'Code', 'marketingName': 'MarketingName'});
}
Code _$CodeFromJson(Map<String, dynamic> json) {
return $checkedNew('Code', json, () {
$checkKeys(json, allowedKeys: const ['SeatsLeft', 'content']);
final val = Code($checkedConvert(json, 'SeatsLeft', (v) => v),
$checkedConvert(json, 'content', (v) => v));
return val;
}, fieldKeyMap: const {'seatLeft': 'SeatsLeft'});
}
Updated
I have looked the api response and I have found that FlightSegmentReference comes in two different ways as bellow shows. How can I design such a format?
{
"Offer": [
{
"PricedOffer": {
"Associations": [
{
"ApplicableFlight": {
"FlightReferences": "Flight1",
"FlightSegmentReference": {
"ref": "99",
"ClassOfService": {
"refs": "ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": " World"
}
},
"OriginDestinationReferences": "OD1"
}
},
{
"ApplicableFlight": {
"FlightReferences": "Flight11",
"FlightSegmentReference": {
"ref": "BA0138",
"ClassOfService": {
"refs": "FBCODE1ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "Club World"
}
},
"OriginDestinationReferences": "OD2"
}
}
]
}
},
{
"PricedOffer": {
"Associations": [
{
"ApplicableFlight": {
"FlightReferences": "Fl",
"FlightSegmentReference": [
{
"ref": "02",
"ClassOfService": {
"refs": "FBCODE2ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "Club World"
}
},
{
"ref": "58",
"ClassOfService": {
"refs": "1ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "B"
}
}
],
"OriginDestinationReferences": "1"
}
},
{
"ApplicableFlight": {
"FlightReferences": "Fl11",
"FlightSegmentReference": {
"ref": "8",
"ClassOfService": {
"refs": "E1ADT",
"Code": {
"SeatsLeft": 9,
"content": "J"
},
"MarketingName": "orld"
}
},
"OriginDestinationReferences": "O"
}
}
]
}
}
]}
List<dynamic> areas = new List();
areas = json.decode(response.body);
String _mySelection1;
Container(
height: 50,
child: DropdownButton<String>(
isExpanded: true,
isDense: true,
hint: new Text("Select Location"),
value: _mySelection1,
onChanged:(String newValue) {
setState(() {
_mySelection1 = newValue;
});
print (_mySelection1);
},
items: areas.map((map){
return DropdownMenuItem<String>(
value: map["area_id"],
child: Text(
map["name"],
),
);
}).toList(),
),
),
here is an example of solution to these kind of problem.. my json also receives Mam response. but i handled it by this way.. hope this example will help you. here is my response.
[{"id":"1","name":"Dermatology"},{"id":"2","name":"Cancer of Female Reproductive System"},{"id":"3","name":"Cardiology"},{"id":"4","name":"Dentistry"},{"id":"5","name":"Allergy & Immunology"},{"id":"6","name":"Anesthesia"},{"id":"7","name":"Colorectal Surgery"},{"id":"8","name":"Endocrinology (Diabetes, Hormones, Thyroid, etc.)"},{"id":"9","name":"ENT (Ear, Nose & Throat, Otorhinolaryngology)"},{"id":"10","name":"Gastroenterology (Stomach, Pancreas and Intestine)"},{"id":"11","name":"General Physician"}]
its in the error message Map for List you need probably List
than it matches and thus can be a subtype