Create dart model class with a dynamic Map<String, dynamic> json - flutter

I have this json i wanna create a model in flutter for a rest api call - but i cannot figure out how the model would look like in dart.
{
"members": [
{
"user": "string",
"joined": 0,
"metadata": {
"some value": "XXXX",
"othervalue": "asddas",
"somethingelse": "dada"
}
}
]
}
Main class
My main class looks like this
`
import "metadata.dart";
class Queuers {
String user;
int joined;
Metadata metadata;
Queuers({this.user, this.joined, this.metadata});
factory Queuers.fromJson(Map<String, dynamic> json) {
return Queuers(
user: json['user'],
joined: json['joined'],
metadata: json['metadata'] != null
? new Metadata.fromJson(json['metadata'])
: null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['user'] = this.user;
data['joined'] = this.joined;
if (this.metadata != null) {
data['metadata'] = this.metadata.toJson();
}
return data;
}
}
`
Metadata class - i trying to parse metadata dynamic data to something else but it fails fails..
class Metadata {
// String additionalProp1;
// String additionalProp2;
// String additionalProp3;
Map<String, dynamic> metadata;
Metadata({this.metadata});
factory Metadata.fromJson(Map<String, dynamic> json) {
return Metadata(
metadata: json['metadata'],
);
// return Metadata(
// additionalProp1: json['additionalProp1'],
// additionalProp2: json['additionalProp2'],
// additionalProp3: json['additionalProp3'],
// );
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['additionalProp1'] = this.additionalProp1;
data['additionalProp2'] = this.additionalProp2;
data['additionalProp3'] = this.additionalProp3;
return data;
}
}
Original code in commented out - im trying to change fromJson method to return a Map of metadata.

Related

How to access JSON via field?

I have a JSON
jsonData
{
"data": {
"splashPage": {
"title": "Splash"
},
"homePage": {
"title": "Home"
}
}
}
List<String> accessField = ['data','splashPage'];
final out = accessField.map((e) => "['$e']").join();
Map jsonMapData = jsonDecode(jsonData);
Map<String, dynamic> splashPageJson = '${jsonMapData}$out' as Map<String, dynamic>;
print(splashPageJson);
I got an error can't access to splashPage.
_CastError (type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast)
How can I access to splashPage from JSON?
Note: accessField is dynamic value
If I want to access splashPage, declaration
accessField = ['data','splashPage'];
If I want to access homePage, declaration
accessField = ['data','homePage'];
Is this what you want?
var jsonData = {
"data": {
"splashPage": {
"title": "Splash"
},
"homePage": {
"title": "Home"
}
}
}
Map jsonMapData = jsonDecode(jsonData);
List<String> accessField = ['data','splashPage'];
Map<String, dynamic> requiredResult = jsonMapData[accessField[0]][accessField[1]];
Here's the solution:
First import:
import 'dart:convert';
To store JSON into the map:
final Map<String, dynamic> map = json.decode('{"data":{"splashPage":{"title":"Splash"},"homePage":{"title":"Home"}}}');
To print your requirement:
print(map["data"]["splashPage"]["title"]);
Code for your Model:
class Model {
Model({
this.data,
});
Model.fromJson(Map<String, dynamic> json) {
data = json["data"] != null ? Data.fromJson(json["data"]) : null;
}
Data? data;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
if (data != null) {
map["data"] = data?.toJson();
}
return map;
}
}
class Data {
Data({
this.splashPage,
this.homePage,
});
Data.fromJson(Map<String, dynamic> json) {
splashPage = json["splashPage"] != null
? SplashPage.fromJson(json["splashPage"])
: null;
homePage =
json["homePage"] != null ? HomePage.fromJson(json["homePage"]) : null;
}
SplashPage? splashPage;
HomePage? homePage;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
if (splashPage != null) {
map["splashPage"] = splashPage?.toJson();
}
if (homePage != null) {
map["homePage"] = homePage?.toJson();
}
return map;
}
}
class HomePage {
HomePage({
this.title,
});
HomePage.fromJson(Map<String, dynamic> json) {
title = json["title"];
}
String? title;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
map["title"] = title;
return map;
}
}
class SplashPage {
SplashPage({
this.title,
});
SplashPage.fromJson(Map<String, dynamic> json) {
title = json["title"];
}
String? title;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
map["title"] = title;
return map;
}
}
Code for your usage:
final Model model = Model.fromJson(
json.decode(
'{"data":{"splashPage":{"title":"Splash"},"homePage":{"title":"Home"}}}',
),
);
print(model.data?.splashPage?.title ?? "");
print(model.data?.homePage?.title ?? "");
Don't forgot to import:
import 'dart:convert';
This is a question about conversion of Json data format to native data model. If you publish the Json data earlier, the problem may not be so complicated
try this.
void test() {
var json =
'{"data":{"splashPage":{"title":"Splash"},"homePage":{"title":"Home"}}}';
var map = jsonDecode(json) as Map<String, dynamic>;
var model = DataResponseModel.fromJson(map);
pr(model.data?.homePage?.title); // Home
pr(model.data?.splashPage?.title); // Splash
}
class TitleModel {
String? title;
TitleModel({required this.title});
factory TitleModel.fromJson(Map<String, dynamic> map) =>
TitleModel(title: map['title']);
}
class DataModel {
TitleModel? splashPage;
TitleModel? homePage;
DataModel({required this.splashPage, this.homePage});
factory DataModel.fromJson(Map<String, dynamic> map) => DataModel(
splashPage: TitleModel.fromJson(map['splashPage']),
homePage: TitleModel.fromJson(map['homePage']),
);
}
class DataResponseModel {
DataModel? data;
DataResponseModel({required this.data});
factory DataResponseModel.fromJson(Map<String, dynamic> map) =>
DataResponseModel(
data: DataModel.fromJson(map['data']),
);
}

Dart : Parse object of Generic type

Response 1:
{
"status" :"ok",
"message":"found",
"data" : {
"key1" :"value1",
"key2" :"value2"
}
}
Response 2 :
{
"status": "ok",
"message": "found",
"data": {
"users": [
{
"key1": "value1",
"key2": "value2"
}
]
}
}
Want to achieve for creating common class with type T.
it can be parsed like this :
Common<List<Data>> commonRes = Common<List<Data>>.fromJson(jsonDecode(res.body));
or
Common<Data> commonRes = Common<Data>.fromJson(jsonDecode(res.body));
Wanted to achieve same as java generic type T.
Anyone knows how to achieve this in dart ?
Tried to create common class like this. but, no luck.
class Common<T> {
String? status;
String? message;
T? data;
Common({
this.status,
this.message,
this.data,
});
Common.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
data = json['data'] as T;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data1 = Map<String, dynamic>();
data1['status'] = this.status;
data1['message'] = this.message;
data1['data'] = this.data;
return data1;
}
}
It becomes apparent rather quickly that what you were trying to do is impossible, as dart has no idea how to convert json['data'] to T and it can't know, a similar thing is the case in the toJson() function.
Usually the way to solve this is by helping them out and providing generator functions, which some of the code generator libraries also do, which I would suggest checking out. Anyway, here is the general idea behind it if you want to implement it yourself, but I recommend using a codegen library as this gets pretty old rather quickly once you have many API calls etc.
import 'dart:convert';
class Common<T> {
String? status;
String? message;
T? data;
Common({
this.status,
this.message,
this.data,
});
Common.fromJson(Map<String, dynamic> json, T Function(Map<String, dynamic>) fromTJSON) {
status = json['status'];
message = json['message'];
data = fromTJSON(json['data']);
}
Map<String, dynamic> toJson(Map<String, dynamic> Function(T?) toTJSON) {
final Map<String, dynamic> data1 = Map<String, dynamic>();
data1['status'] = status;
data1['message'] = message;
data1['data'] = toTJSON(data);
return data1;
}
}
class ClassA {
String? a;
ClassA({this.a});
ClassA.fromJson(Map<String, dynamic> json) {
a = json['a'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data1 = Map<String, dynamic>();
data1['a'] = a;
return data1;
}
}
class ClassB {
String? b;
ClassB({this.b});
ClassB.fromJson(Map<String, dynamic> json) {
b = json['b'];
}
static ClassB? generatorFoo(Map<String, dynamic> json) {
return null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data1 = Map<String, dynamic>();
data1['b'] = b;
return data1;
}
}
int main() {
String c1JSON = '''
{
"status" :"ok",
"message":"found",
"data" : {
"a" :"someA"
}
}
''';
String c2JSON = '''
{
"status" :"ok",
"message":"found",
"data" : {
"b" :"someb"
}
}
''';
Map<String,dynamic> map1 = jsonDecode(c1JSON);
Common<ClassA> cA = Common.fromJson(map1, (map) => ClassA.fromJson(map));
print(cA.toJson((obj) => obj != null ? obj.toJson() : {}));
Map<String,dynamic> map2 = jsonDecode(c2JSON);
Common<ClassB> cB = Common.fromJson(map2, (map) => ClassB.fromJson(map));
print(cB.toJson((obj) => obj != null ? obj.toJson() : {}));
return 0;
}
In your case you will also need to write a function to help with the mapping of the lists, the general idea is to provide a generator function so you can encode and decode the nested generic types.

How to write the model for the JOSN ? Flutter

I have a Google maps API where in i was trying to save the place key and the JSON response of that particular place in the SQFLite. I was able to write the fromJSON method but how to write the toMap method?
This is the model without the toMap method
class GeometryModel {
final LocationModel locationModel;
GeometryModel({required this.locationModel});
factory GeometryModel.fromJson(Map<dynamic, dynamic> parsedJson) {
return GeometryModel(locationModel: LocationModel.fromJson(parsedJson['location']));
}
}
class LocationModel {
final double latitude;
final double longitude;
LocationModel({required this.latitude, required this.longitude});
factory LocationModel.fromJson(Map<dynamic, dynamic> parsedJson) {
return LocationModel(latitude: parsedJson['lat'], longitude: parsedJson['lng']);
}
}
class PlaceModel {
final String placeId;
final GeometryModel geometryModel;
final String address;
final String name;
PlaceModel({required this.placeId, required this.geometryModel, required this.address, required this.name});
factory PlaceModel.fromJson(Map<String, dynamic> parsedJson) {
return PlaceModel(
placeId: parsedJson['place_id'],
name: parsedJson['vicinity'],
geometryModel: GeometryModel.fromJson(parsedJson['geometry']),
address: parsedJson['formatted_address'],
);
}
}
This is the response I'm receiving from the server
{
"html_attributions": [],
"result": {
"formatted_address": "New York, NY, USA",
"geometry": {
"location": {
"lat": 40.7127753,
"lng": -74.0059728
},
"viewport": {
"northeast": {
"lat": 40.91757705070789,
"lng": -73.70027206817629
},
"southwest": {
"lat": 40.47739906045452,
"lng": -74.25908991427882
}
}
},
"icon_background_color": "#7B9EB0",
"icon_mask_base_uri": "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet",
"name": "New York"
"url": "https://maps.google.com/?q=New+York,+NY,+USA&ftid=0x89c24fa5d33f083b:0xc80b8f06e177fe62",
"utc_offset": -240,
"vicinity": "New York","
},
"status": "OK"
}
Use JsonToDart website. You just need to paste your JSON data and it will convert json data to model class along with fromJson() and toJson() or toMap().
NOTE: If you get json syntax error you need to verify your json data is Valid or not. For json validation check json_parser_online website.
There's another option to work with JSON data and without creating models and without using generators! How? Using the g-json package.
See my answer to another question (How to parse complex JSON using default methods in Flutter?) that can help you, Naan Avan.
Here is the example of Viewport, how to convert toJson/toMap and use this link to help you to convert your JSON to map
class Viewport {
Viewport viewport;
Viewport({this.viewport});
Viewport.fromJson(Map<String, dynamic> json) {
viewport = json['viewport'] != null
? new Viewport.fromJson(json['viewport'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.viewport != null) {
data['viewport'] = this.viewport.toJson();
}
return data;
}
}
class Viewport {
Northeast northeast;
Northeast southwest;
Viewport({this.northeast, this.southwest});
Viewport.fromJson(Map<String, dynamic> json) {
northeast = json['northeast'] != null
? new Northeast.fromJson(json['northeast'])
: null;
southwest = json['southwest'] != null
? new Northeast.fromJson(json['southwest'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.northeast != null) {
data['northeast'] = this.northeast.toJson();
}
if (this.southwest != null) {
data['southwest'] = this.southwest.toJson();
}
return data;
}
}
class Northeast {
double lat;
double lng;
Northeast({this.lat, this.lng});
Northeast.fromJson(Map<String, dynamic> json) {
lat = json['lat'];
lng = json['lng'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['lat'] = this.lat;
data['lng'] = this.lng;
return data;
}
}
You can achieve it like this :
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
map['place_id'] = placeId;
map['address'] = address;
map['name'] = name;
map['geometry_model_id']=geometryModel.id; //saves id
return map;}

I want to retrive each entity from following data in flutter

I want to sort each entity from following data in flutter
i.e enrollment_no,nationality,mother this data is coming from api
"personal":
"{\"enrollment_no\":\"1701\",
\"nationality\":\"INDIAN\",
\"driver_mobile\":\"-\",
\"mother\":\"JAGRUTIBAHEN SHRIKANT SONI\",
\"email\":\"SHRIKANT206#YAHOO.CO.IN\",
\"student_photo\":\"/container/school_data/BRS/photo/Student/1701.jpg\",
\"name\":\"NEYSA SHRIKANT SONI\",
\"mother_mobile\":\"+971507603564\",
\"father_mobile\":\"+971503171294\",
\"father\":\"SHRIKANT INDUKANT SONI\"}",
//I trying following code to sort data but can't achieve
if(personal == data['personal']) {
for (int i = 0; i < data['personal'].length; i++)
{
arrayp = personal;
print(arrayp);
var array1=arrayp[0]['father'];
print(array1);
}
}
1. Your JSON from API
{
"personal":
{
"enrollment_no": "1701",
"nationality": "INDIAN",
"driver_mobile": "-",
"mother": "JAGRUTIBAHEN SHRIKANT SONI",
"email": "SHRIKANT206#YAHOO.CO.IN",
"student_photo": "/container/school_data/BRS/photo/Student/1701.jpg",
"name": "NEYSA SHRIKANT SONI",
"mother_mobile": "+971507603564",
"father_mobile": "+971503171294",
"father": "SHRIKANT INDUKANT SONI"
}
}
2. Go To https://javiercbk.github.io/json_to_dart/
Convert your Json to Dart Classes.
class Personal {
PersonalData personal;
Personal({this.personal});
factory Personal.fromJson(Map<String, dynamic> json) {
return Personal(
personal: json['personal'] != null ?
PersonalData.fromJson(json['personal']) : null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.personal != null) {
data['personal'] = this.personal.toJson();
}
return data;
}
}
class PersonalData {
String driver_mobile;
String email;
String enrollment_no;
String father;
String father_mobile;
String mother;
String mother_mobile;
String name;
String nationality;
String student_photo;
PersonalData({this.driver_mobile, this.email, this.enrollment_no, this.father, this.father_mobile, this.mother, this.mother_mobile, this.name, this.nationality, this.student_photo});
factory PersonalData.fromJson(Map<String, dynamic> json) {
return PersonalData(
driver_mobile: json['driver_mobile'],
email: json['email'],
enrollment_no: json['enrollment_no'],
father: json['father'],
father_mobile: json['father_mobile'],
mother: json['mother'],
mother_mobile: json['mother_mobile'],
name: json['name'],
nationality: json['nationality'],
student_photo: json['student_photo'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['driver_mobile'] = this.driver_mobile;
data['email'] = this.email;
data['enrollment_no'] = this.enrollment_no;
data['father'] = this.father;
data['father_mobile'] = this.father_mobile;
data['mother'] = this.mother;
data['mother_mobile'] = this.mother_mobile;
data['name'] = this.name;
data['nationality'] = this.nationality;
data['student_photo'] = this.student_photo;
return data;
}
}
3. Now time for you api response
_getResponseFromApi() asyn{
var response = await http.post({your parameters})
var data = Personal.fromJson(json.decode(response.body));
var listOfPersonData = data.personal
}

How to convert an array to a dart object

I have the following structure that is returned from my API. How do I convert it to a dart object?
[
{
"stateName": "Alabama",
"stateAbbr": "AL"
},
{
"stateName": "Alaska",
"stateAbbr": "AK"
}
]
Basically, I want to display a flutter dropdown box with the stateName value..
It's a list of maps.
first make a State class:
class State{
final String stateName;
final String stateAbbr;
State({
this.stateName,
this.stateAbbr,
}) ;
factory State.fromJson(Map<String, dynamic> json){
return new State(
id: json['stateName'],
title: json['stateAbbr'],
);
}
}
then list of States:
class StatesList {
final List<State> States;
StatesList({
this.States,
});
factory StatesList.fromJson(List<dynamic> parsedJson) {
List<State> States = new List<State>();
States = parsedJson.map((i)=>State.fromJson(i)).toList();
return new StatesList(
States: States,
);
}
}
for more information read this article
class State {
String stateName;
String stateAbbr;
State({this.stateName, this.stateAbbr});
State.fromJson(Map<String, dynamic> json) {
stateName = json['stateName'];
stateAbbr = json['stateAbbr'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['stateName'] = this.stateName;
data['stateAbbr'] = this.stateAbbr;
return data;
}
}
use this website [https://javiercbk.github.io/json_to_dart/][1] it can help you to convert any object JSON to Dart class, and after that, you should use List Object of type State.