I am currently trying to parse this json string:
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
I created this class:
class ParseJSON {
ParseJSON({
this.imsak,
this.sunrise,
this.fajr,
this.dhuhr,
this.asr,
this.sunset,
this.maghrib,
this.isha,
this.midnight,
});
String imsak;
String sunrise;
String fajr;
String dhuhr;
String asr;
String sunset;
String maghrib;
String isha;
String midnight;
factory ParseJSON.fromJson(Map<String, dynamic> json) => ParseJSON(
imsak: json["Imsak"],
sunrise: json["Sunrise"],
fajr: json["Fajr"],
dhuhr: json["Dhuhr"],
asr: json["Asr"],
sunset: json["Sunset"],
maghrib: json["Maghrib"],
isha: json["Isha"],
midnight: json["Midnight"],
);
Map<String, dynamic> toJson() => {
"Imsak": imsak,
"Sunrise": sunrise,
"Fajr": fajr,
"Dhuhr": dhuhr,
"Asr": asr,
"Sunset": sunset,
"Maghrib": maghrib,
"Isha": isha,
"Midnight": midnight,
};
}
I tried to access the contents of the json thus:
Future<List<ParseJSON>> fetchJSON() async {
String jsonResponse = """
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
""";
ParseJSON welcomeFromJson(String str) => ParseJSON.fromJson(json.decode(str));
final welcome = welcomeFromJson(jsonResponse);
print("Printing contents from json string");
//print(jsonResponse);
print(welcome.maghrib);
print(welcome.fajr);
}
The problem is that both print(welcome.maghrib) and print(welcome.fajr) return null. Please what am i doing incorrectly? Any help would be appreciated. Thanks
Your model class is for only getting "times" object, so you need below change for parsing Json or you need to change your model class for parsing every field from Response.
Future<List<ParseJSON>?> fetchJSON() async {
String jsonResponse = """
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
""";
var response = json.decode(jsonResponse);
ParseJSON welcome = ParseJSON.fromJson(response['results']['datetime'][0]['times']);
print("Printing contents from json string");
//print(jsonResponse);
print(welcome.maghrib);
print(welcome.fajr);
}
You can try out using this code :
import 'dart:convert';
ParseJson parseJsonFromJson(String str) => ParseJson.fromJson(json.decode(str));
String parseJsonToJson(ParseJson data) => json.encode(data.toJson());
class ParseJson {
ParseJson({
this.code,
this.status,
this.results,
});
int code;
String status;
Results results;
factory ParseJson.fromJson(Map<String, dynamic> json) => ParseJson(
code: json["code"],
status: json["status"],
results: Results.fromJson(json["results"]),
);
Map<String, dynamic> toJson() => {
"code": code,
"status": status,
"results": results.toJson(),
};
}
class Results {
Results({
this.datetime,
this.location,
this.settings,
});
List<Datetime> datetime;
Location location;
Settings settings;
factory Results.fromJson(Map<String, dynamic> json) => Results(
datetime: List<Datetime>.from(json["datetime"].map((x) => Datetime.fromJson(x))),
location: Location.fromJson(json["location"]),
settings: Settings.fromJson(json["settings"]),
);
Map<String, dynamic> toJson() => {
"datetime": List<dynamic>.from(datetime.map((x) => x.toJson())),
"location": location.toJson(),
"settings": settings.toJson(),
};
}
class Datetime {
Datetime({
this.times,
this.date,
});
Times times;
Date date;
factory Datetime.fromJson(Map<String, dynamic> json) => Datetime(
times: Times.fromJson(json["times"]),
date: Date.fromJson(json["date"]),
);
Map<String, dynamic> toJson() => {
"times": times.toJson(),
"date": date.toJson(),
};
}
class Date {
Date({
this.timestamp,
this.gregorian,
this.hijri,
});
int timestamp;
DateTime gregorian;
DateTime hijri;
factory Date.fromJson(Map<String, dynamic> json) => Date(
timestamp: json["timestamp"],
gregorian: DateTime.parse(json["gregorian"]),
hijri: DateTime.parse(json["hijri"]),
);
Map<String, dynamic> toJson() => {
"timestamp": timestamp,
"gregorian": "${gregorian.year.toString().padLeft(4, '0')}-${gregorian.month.toString().padLeft(2, '0')}-${gregorian.day.toString().padLeft(2, '0')}",
"hijri": "${hijri.year.toString().padLeft(4, '0')}-${hijri.month.toString().padLeft(2, '0')}-${hijri.day.toString().padLeft(2, '0')}",
};
}
class Times {
Times({
this.imsak,
this.sunrise,
this.fajr,
this.dhuhr,
this.asr,
this.sunset,
this.maghrib,
this.isha,
this.midnight,
});
String imsak;
String sunrise;
String fajr;
String dhuhr;
String asr;
String sunset;
String maghrib;
String isha;
String midnight;
factory Times.fromJson(Map<String, dynamic> json) => Times(
imsak: json["Imsak"],
sunrise: json["Sunrise"],
fajr: json["Fajr"],
dhuhr: json["Dhuhr"],
asr: json["Asr"],
sunset: json["Sunset"],
maghrib: json["Maghrib"],
isha: json["Isha"],
midnight: json["Midnight"],
);
Map<String, dynamic> toJson() => {
"Imsak": imsak,
"Sunrise": sunrise,
"Fajr": fajr,
"Dhuhr": dhuhr,
"Asr": asr,
"Sunset": sunset,
"Maghrib": maghrib,
"Isha": isha,
"Midnight": midnight,
};
}
class Location {
Location({
this.latitude,
this.longitude,
this.elevation,
this.city,
this.country,
this.countryCode,
this.timezone,
this.localOffset,
});
double latitude;
double longitude;
int elevation;
String city;
String country;
String countryCode;
String timezone;
int localOffset;
factory Location.fromJson(Map<String, dynamic> json) => Location(
latitude: json["latitude"].toDouble(),
longitude: json["longitude"].toDouble(),
elevation: json["elevation"],
city: json["city"],
country: json["country"],
countryCode: json["country_code"],
timezone: json["timezone"],
localOffset: json["local_offset"],
);
Map<String, dynamic> toJson() => {
"latitude": latitude,
"longitude": longitude,
"elevation": elevation,
"city": city,
"country": country,
"country_code": countryCode,
"timezone": timezone,
"local_offset": localOffset,
};
}
class Settings {
Settings({
this.timeformat,
this.school,
this.juristic,
this.highlat,
this.fajrAngle,
this.ishaAngle,
});
String timeformat;
String school;
String juristic;
String highlat;
int fajrAngle;
int ishaAngle;
factory Settings.fromJson(Map<String, dynamic> json) => Settings(
timeformat: json["timeformat"],
school: json["school"],
juristic: json["juristic"],
highlat: json["highlat"],
fajrAngle: json["fajr_angle"],
ishaAngle: json["isha_angle"],
);
Map<String, dynamic> toJson() => {
"timeformat": timeformat,
"school": school,
"juristic": juristic,
"highlat": highlat,
"fajr_angle": fajrAngle,
"isha_angle": ishaAngle,
};
}
just call this line when parse json:
final parseJson = parseJsonFromJson(jsonString);
like bellow:
Future<void> fetchJSON() async {
String jsonResponse = """
{"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
""";
final welcome = jsonParseFromJson(jsonResponse);
print("Printing contents from json string");
//print(jsonResponse);
print(welcome.results.datetime[0].times.fajr);
}
Related
I am trying to do backup of hive box data to a json file, so that I can use it for restoring data if data is lost,
I am calling a function with on pressed of text button to do this task.
but I am getting an error regarding converting failure.
Converting object to an encodable object failed: Instance of 'TransactionModel'
here are models
#HiveType(typeId: 0)
class CategoryModel extends HiveObject
{
#HiveField(0)
String title;
#HiveField(1)
String iconurl;
CategoryModel({required this.title, required this.iconurl});
Map<String, dynamic> toJson() {
return {
'title': title,
'iconurl': iconurl,
};
}
factory CategoryModel.fromjson(Map<String, dynamic> map) {
return CategoryModel(
title: map['title'],
iconurl: map['iconurl']);
}
}
and
#HiveType(typeId: 1)
class TransactionModel extends HiveObject{
#HiveField(0)
String id;
#HiveField(1)
CategoryModel category;
#HiveField(2)
String paymentmode;
#HiveField(3)
bool isexpense;
#HiveField(4)
DateTime date;
#HiveField(5)
String note;
#HiveField(6)
double amount;
TransactionModel(
{
this.amount = 0.00,
required this.id,
required this.category,
required this.paymentmode,
this.isexpense = true,
required this.date,
this.note = 'No Note'});
Map<String, dynamic> toJson() {
return {
'id': id,
'category': category.toJson(),
'paymentmode': paymentmode,
'isexpense': isexpense,
'date': date,
'note':note,
'amount':amount,
};
}
factory TransactionModel.fromjson(Map<String, dynamic> map) {
return TransactionModel(
id: map['id'],
category: CategoryModel.fromjson(map['category']),
paymentmode: map['paymentmode'],
isexpense: map['isexpense'],
date: map['date'],
note: map['note'],
amount:map['amount'],
);
}
}
Here is the function for creating backup file of hive box data
Future<void> _createBackupFile() async {
File backupFile = File('${Directory.systemTemp.path}/logic.json');
try {
await backupFile.writeAsString(jsonEncode(Hive.box<TransactionModel>('ebook').values));
} catch (e) {
print('Error is :'+e.toString());
}
}
I found my mistake...
it can not encode directly to some custom datatype like DateTime, so need to convert into map before encode...
Map<String, dynamic> toJson() {
return {
'id': id,
'category': category.toJson(),
'paymentmode': paymentmode,
'isexpense': isexpense,
'date': date.toString(),//corrected from date to date.toString()
'note':note,
'amount':amount,
};
}
I'm pulling my data from MongoDB with a Future. However, I want to pull only some of the data, not the whole data. How can I filter this?
I will put the data I filtered into the list. I added the readMongo and lessonModel codes.
In addition, although my codes work very well, I think that I did not do something according to the rules, if I am missing, I would be very happy if you could point out.
Future<List<Map<String, dynamic>>> _getData() async {
values = MongoDatabase.readMongo(MongoDatabase.lessonCollection);
return values!;
}
readMongo
static Future<List<Map<String, dynamic>>> readMongo(collectionName) async {
final data = await collectionName.find().toList();
return data;
}
LessonModel
import 'dart:convert';
LessonModel lessonModelFromMap(String str) => LessonModel.fromMap(json.decode(str));
String lessonModelToMap(LessonModel data) => json.encode(data.toMap());
class LessonModel {
LessonModel({this.id, this.info, this.subject});
final Id? id;
final Info? info;
final List<Subject>? subject;
factory LessonModel.fromMap(Map<String, dynamic> json) => LessonModel(
info: json["info"] == null ? null : Info.fromMap(json["info"]),
subject: json["subject"] == null ? null : List<Subject>.from(json["subject"].map((x) => Subject.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"_id": id == null ? null : id!.toMap(),
"info": info == null ? null : info!.toMap(),
"subject": subject == null ? null : List<dynamic>.from(subject!.map((x) => x.toMap())),
};
}
class Id {
Id({this.oid});
final String? oid;
factory Id.fromMap(Map<String, dynamic> json) => Id(oid: json["\u0024oid"]);
Map<String, dynamic> toMap() => {"\u0024oid": oid};
}
class Info {
Info({this.name, this.infoClass, this.semester, this.credit, this.icon});
final String? name;
final String? infoClass;
final String? semester;
final int? credit;
final String? icon;
factory Info.fromMap(Map<String, dynamic> json) => Info(
name: json["name"],
infoClass: json["class"],
semester: json["semester"],
credit: json["credit"],
icon: json["icon"]);
Map<String, dynamic> toMap() =>
{"name": name, "class": infoClass, "semester": semester, "credit": credit, "icon": icon};
}
class Subject {
Subject({this.subjectId, this.name, this.text, this.video, this.trainer});
final int? subjectId;
final String? name;
final String? text;
final String? video;
final String? trainer;
factory Subject.fromMap(Map<String, dynamic> json) => Subject(
subjectId: json["subjectId"],
name: json["name"],
text: json["text"],
video: json["video"],
trainer: json["trainer"]);
Map<String, dynamic> toMap() =>
{"subjectId": subjectId, "name": name, "text": text, "video": video, "trainer": trainer};
}
How to fetch data from the model that look like this http://lovemonster.my.id/hospital to my BLoC builder in form of list? i got an error message when i fetch it Type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' and this is my provider:
class ApiProvider {
final Dio _dio = Dio();
final String _url = 'http://lovemonster.my.id/hospital';
Future<HospitalListModel> fetchHospitalList() async {
try {
Response response = await _dio.get(_url);
return HospitalListModel.fromJson(response.data);
} catch (error, stacktrace) {
print("Exception occurred: $error stackTrace: $stacktrace");
return Future.error("");
}
}
}
and this is my repository:
class ApiRepository {
final _provider = ApiProvider();
Future<HospitalListModel> fetchHospitalList() {
return _provider.fetchHospitalList();
}
}
class NetworkError extends Error {}
this is the model, in case you want to know how it looks like:
class HospitalListModel {
int? id;
String? title;
String? content;
String? image;
String? phone;
String? coordinates;
String? website;
String? createdAt;
String? updatedAt;
HospitalListModel({
this.id,
this.title,
this.content,
this.image,
this.phone,
this.coordinates,
this.website,
this.createdAt,
this.updatedAt,
});
HospitalListModel.fromJson(Map<String, dynamic> json) {
id = json['id'] as int?;
title = json['title'] as String?;
content = json['content'] as String?;
image = json['image'] as String?;
phone = json['phone'] as String?;
coordinates = json['coordinates'] as String?;
website = json['website'] as String?;
createdAt = json['created_at'] as String?;
updatedAt = json['updated_at'] as String?;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> json = <String, dynamic>{};
json['id'] = id;
json['title'] = title;
json['content'] = content;
json['image'] = image;
json['phone'] = phone;
json['coordinates'] = coordinates;
json['website'] = website;
json['created_at'] = createdAt;
json['updated_at'] = updatedAt;
return json;
}
}
can anyone show me how to fetch the data from my API
// To parse this JSON data, do
//
// final hospitalListModel = hospitalListModelFromJson(jsonString);
import 'dart:convert';
List<HospitalListModel> hospitalListModelFromJson(String str) => List<HospitalListModel>.from(json.decode(str).map((x) => HospitalListModel.fromJson(x)));
String hospitalListModelToJson(List<HospitalListModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class HospitalListModel {
HospitalListModel({
this.id,
this.title,
this.content,
this.image,
this.phone,
this.coordinates,
this.website,
this.createdAt,
this.updatedAt,
});
dynamic id;
dynamic title;
dynamic content;
dynamic image;
dynamic phone;
dynamic coordinates;
dynamic website;
dynamic createdAt;
dynamic updatedAt;
factory HospitalListModel.fromJson(Map<String, dynamic> json) => HospitalListModel(
id: json["id"],
title: json["title"],
content: json["content"],
image: json["image"],
phone: json["phone"],
coordinates: json["coordinates"],
website: json["website"],
createdAt: json["created_at"],
updatedAt: json["updated_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"content": content,
"image": image,
"phone": phone,
"coordinates": coordinates,
"website": website,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
call this from here
final hospitalListModel = hospitalListModelFromJson(jsonString);
Example:
Future<List<HospitalListModel>> fetchHospitalList() async {
try {
Response response = await _dio.get(_url);
return hospitalListModelFromJson(response.body);
} catch (error, stacktrace) {
print("Exception occurred: $error stackTrace: $stacktrace");
return Future.error("");
}
}
I work with flutter not so long and i don't know how to retrieve data as same as I described below.
I create an app with API. I received all data except Gallery images, program, additionalInfo.
Can anyone explain to me how I can retrieve gallery images, program and additionalInfo from API?
If you can write code snippets which I can use. Thanks.
'https://tripvenue.ru/api/v1/experiences/448'
import 'dart:convert';
ExperiencesByCityId experiencesByCityIdFromJson(String str) =>
ExperiencesByCityId.fromJson(json.decode(str));
String experiencesByCityIdToJson(ExperiencesByCityId data) =>
json.encode(data.toJson());
class ExperiencesByCityId {
ExperiencesByCityId({
this.id,
this.title,
this.promoText,
this.country,
this.city,
this.mainPhoto,
this.type,
this.languages,
this.instantBooking,
this.duration,
this.votesCount,
this.votesAvg,
this.url,
this.pricing,
this.teaserText,
this.description,
this.program,
this.additionalInfo,
this.gallery,
this.guestsMin,
this.guestsMax,
});
int id;
String title;
String promoText;
City country;
City city;
MainPhoto mainPhoto;
String type;
List<String> languages;
bool instantBooking;
int duration;
int votesCount;
double votesAvg;
String url;
Pricing pricing;
String teaserText;
String description;
List<Program> program;
List<String> additionalInfo;
List<Gallery> gallery;
int guestsMin;
int guestsMax;
factory ExperiencesByCityId.fromJson(Map<String, dynamic> json) =>
ExperiencesByCityId(
id: json["id"],
title: json["title"],
promoText: json["promo_text"],
country: City.fromJson(json["country"]),
city: City.fromJson(json["city"]),
mainPhoto: MainPhoto.fromJson(json["main_photo"]),
type: json["type"],
languages: List<String>.from(json["languages"].map((x) => x)),
instantBooking: json["instant_booking"],
duration: json["duration"],
votesCount: json["votes_count"],
votesAvg: json["votes_avg"],
url: json["url"],
pricing: Pricing.fromJson(json["pricing"]),
teaserText: json["teaser_text"],
description: json["description"],
program:
List<Program>.from(json["program"].map((x) => Program.fromJson(x))),
additionalInfo:
List<String>.from(json["additional_info"].map((x) => x)),
gallery:
List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
guestsMin: json["guests_min"],
guestsMax: json["guests_max"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"promo_text": promoText,
"country": country.toJson(),
"city": city.toJson(),
"main_photo": mainPhoto.toJson(),
"type": type,
"languages": List<dynamic>.from(languages.map((x) => x)),
"instant_booking": instantBooking,
"duration": duration,
"votes_count": votesCount,
"votes_avg": votesAvg,
"url": url,
"pricing": pricing.toJson(),
"teaser_text": teaserText,
"description": description,
"program": List<dynamic>.from(program.map((x) => x.toJson())),
"additional_info": List<dynamic>.from(additionalInfo.map((x) => x)),
"gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
"guests_min": guestsMin,
"guests_max": guestsMax,
};
}
class City {
City({
this.id,
this.name,
});
int id;
String name;
factory City.fromJson(Map<String, dynamic> json) => City(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
class Gallery {
Gallery({
this.fid,
this.uri,
this.url,
});
int fid;
String uri;
String url;
factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
fid: json["fid"],
uri: json["uri"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"fid": fid,
"uri": uri,
"url": url,
};
}
class MainPhoto {
MainPhoto({
this.id,
this.uri,
this.url,
});
int id;
String uri;
String url;
factory MainPhoto.fromJson(Map<String, dynamic> json) => MainPhoto(
id: json["id"],
uri: json["uri"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"id": id,
"uri": uri,
"url": url,
};
}
class Pricing {
Pricing({
this.type,
this.amount,
this.currency,
this.formatted,
this.groupSizeMin,
this.groupSizeMax,
});
String type;
double amount;
String currency;
String formatted;
int groupSizeMin;
int groupSizeMax;
factory Pricing.fromJson(Map<String, dynamic> json) => Pricing(
type: json["type"],
amount: json["amount"],
currency: json["currency"],
formatted: json["formatted"],
groupSizeMin: json["group_size_min"],
groupSizeMax: json["group_size_max"],
);
Map<String, dynamic> toJson() => {
"type": type,
"amount": amount,
"currency": currency,
"formatted": formatted,
"group_size_min": groupSizeMin,
"group_size_max": groupSizeMax,
};
}
class Program {
Program({
this.first,
this.second,
});
String first;
Second second;
factory Program.fromJson(Map<String, dynamic> json) => Program(
first: json["first"],
second: secondValues.map[json["second"]],
);
Map<String, dynamic> toJson() => {
"first": first,
"second": secondValues.reverse[second],
};
}
enum Second { EMPTY, SECOND, PURPLE }
final secondValues = EnumValues({
"": Second.EMPTY,
"по возможности посмотрим их на закате": Second.PURPLE,
"здесь вы сделаете классные фото на заброшке": Second.SECOND
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
You can generate your Response class from https://jsontodart.com
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: TextButton(
onPressed: () async {
var response = await http.get(
Uri.parse('https://tripvenue.ru/api/v1/experiences/448'));
var body = response.body;
Response myResponse = Response.fromJson(json.decode(body));
print(myResponse.gallery.first.url);
},
child: Text(
"press",
),
),
)));
}
}
class Response {
int id;
String title;
String promoText;
Country country;
Country city;
MainPhoto mainPhoto;
String type;
List<String> languages;
bool instantBooking;
int duration;
int votesCount;
double votesAvg;
String url;
Pricing pricing;
String teaserText;
String description;
List<Program> program;
List<String> additionalInfo;
List<Gallery> gallery;
int guestsMin;
int guestsMax;
Response(
{this.id,
this.title,
this.promoText,
this.country,
this.city,
this.mainPhoto,
this.type,
this.languages,
this.instantBooking,
this.duration,
this.votesCount,
this.votesAvg,
this.url,
this.pricing,
this.teaserText,
this.description,
this.program,
this.additionalInfo,
this.gallery,
this.guestsMin,
this.guestsMax});
Response.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
promoText = json['promo_text'];
country =
json['country'] != null ? new Country.fromJson(json['country']) : null;
city = json['city'] != null ? new Country.fromJson(json['city']) : null;
mainPhoto = json['main_photo'] != null
? new MainPhoto.fromJson(json['main_photo'])
: null;
type = json['type'];
languages = json['languages'].cast<String>();
instantBooking = json['instant_booking'];
duration = json['duration'];
votesCount = json['votes_count'];
votesAvg = json['votes_avg'];
url = json['url'];
pricing =
json['pricing'] != null ? new Pricing.fromJson(json['pricing']) : null;
teaserText = json['teaser_text'];
description = json['description'];
if (json['program'] != null) {
program = <Program>[];
json['program'].forEach((v) {
program.add(new Program.fromJson(v));
});
}
additionalInfo = json['additional_info'].cast<String>();
if (json['gallery'] != null) {
gallery = <Gallery>[];
json['gallery'].forEach((v) {
gallery.add(new Gallery.fromJson(v));
});
}
guestsMin = json['guests_min'];
guestsMax = json['guests_max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['promo_text'] = this.promoText;
if (this.country != null) {
data['country'] = this.country.toJson();
}
if (this.city != null) {
data['city'] = this.city.toJson();
}
if (this.mainPhoto != null) {
data['main_photo'] = this.mainPhoto.toJson();
}
data['type'] = this.type;
data['languages'] = this.languages;
data['instant_booking'] = this.instantBooking;
data['duration'] = this.duration;
data['votes_count'] = this.votesCount;
data['votes_avg'] = this.votesAvg;
data['url'] = this.url;
if (this.pricing != null) {
data['pricing'] = this.pricing.toJson();
}
data['teaser_text'] = this.teaserText;
data['description'] = this.description;
if (this.program != null) {
data['program'] = this.program.map((v) => v.toJson()).toList();
}
data['additional_info'] = this.additionalInfo;
if (this.gallery != null) {
data['gallery'] = this.gallery.map((v) => v.toJson()).toList();
}
data['guests_min'] = this.guestsMin;
data['guests_max'] = this.guestsMax;
return data;
}
}
class Country {
int id;
String name;
Country({this.id, this.name});
Country.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;
}
}
class MainPhoto {
int id;
String uri;
String url;
MainPhoto({this.id, this.uri, this.url});
MainPhoto.fromJson(Map<String, dynamic> json) {
id = json['id'];
uri = json['uri'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['uri'] = this.uri;
data['url'] = this.url;
return data;
}
}
class Pricing {
String type;
double amount;
String currency;
String formatted;
int groupSizeMin;
int groupSizeMax;
Pricing(
{this.type,
this.amount,
this.currency,
this.formatted,
this.groupSizeMin,
this.groupSizeMax});
Pricing.fromJson(Map<String, dynamic> json) {
type = json['type'];
amount = json['amount'];
currency = json['currency'];
formatted = json['formatted'];
groupSizeMin = json['group_size_min'];
groupSizeMax = json['group_size_max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['amount'] = this.amount;
data['currency'] = this.currency;
data['formatted'] = this.formatted;
data['group_size_min'] = this.groupSizeMin;
data['group_size_max'] = this.groupSizeMax;
return data;
}
}
class Program {
String first;
String second;
Program({this.first, this.second});
Program.fromJson(Map<String, dynamic> json) {
first = json['first'];
second = json['second'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['first'] = this.first;
data['second'] = this.second;
return data;
}
}
class Gallery {
int fid;
String uri;
String url;
Gallery({this.fid, this.uri, this.url});
Gallery.fromJson(Map<String, dynamic> json) {
fid = json['fid'];
uri = json['uri'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['fid'] = this.fid;
data['uri'] = this.uri;
data['url'] = this.url;
return data;
}
}
In my Flutter app I receive notifications with a custom payload, like:
{ notification:
{
title: Test,
body: AAAA
},
data:
{
productId: Axe,
page: Products,
click_action: FLUTTER_NOTIFICATION_CLICK
}
}
Everything works well. I also can handle the payload of the notification by access it through:
message['data']['page']
But I rather would like to use an Interface/Class to name the data by key, for example:
message.data.page and message.data.productId
So I tried:
class NotificationMessage {
Map notification;
Map data;
NotificationMessage(this.notification, this.data);
}
...
NotificationMessage _message = message; // Assigning the payload to the final
...
This where I get stuck: here I got the error: A value of type 'Map<dynamic, dynamic>' can't be assigned to a variable of type 'NotificationMessage'.
My class isn't finished yet, but how to continue?
I' aware of json_serializable, but before any tooling, I would like to understand it fully.
First, you need to build the two models for notification and data as follows
class DataMessage {
final String productId;
final String page;
final String click_action;
DataMessage(this.productId, this.page, this.click_action);
factory DataMessage.fromJson(Map<dynamic, dynamic> json) {
return DataMessage(
json['productId'] as String,
json['page'] as String,
json['click_action'] as String,
);
}
}
class NotificationMessage {
final String title;
final String body;
NotificationMessage(this.title, this.body);
factory NotificationMessage.fromJson(Map<dynamic, dynamic> json) {
return NotificationMessage(
json['title'] as String,
json['body'] as String,
);
}
}
The factory method convert map types into model classes.
Then you have to build a model for the response message as follows
class Message {
final NotificationMessage notification;
final DataMessage data;
Message(this.notification, this.data);
factory Message.fromJson(Map<dynamic, dynamic> json) {
final Map<dynamic, dynamic> mapNotification = json['notification'];
final Map<dynamic, dynamic> mapData = json['data'];
final dataModel = DataMessage.fromJson(mapData);
final notificationModel = NotificationMessage.fromJson(mapNotification);
return Message(
notificationModel as NotificationMessage,
dataModel as DataMessage,
);
}
}
Note that the factory method allows you to convert the maps for each model to a class model
So you can define your response as a class
Map<dynamic, dynamic> messageResponse = {
'notification': {'title': 'Test', 'body': 'AAAA'},
'data': {
'productId': 'Axe',
'page': 'Products',
'click_action': 'FLUTTER_NOTIFICATION_CLICK'
}
};
final Message message = Message.fromJson(messageResponse);
print(message.data.productId);
print(message.data.page);
print(message.data.click_action);
print(message.notification.title);
print(message.notification.body);
Hope that can help you
Instance of the json object. this way you can use a map for any instance without modifying the class
{ "notification":
{
"title": "Test",
"body": "AAAA"
},
"data":
{
"productId": "Axe",
"page": "Products",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
}
Class looks like;
class NotificationMessage {
NotificationMessage({
this.notification,
this.data,
});
final Notification notification;
final Data data;
factory NotificationMessage.fromJson(Map<String, dynamic> json) => NotificationMessage(
notification: Notification.fromJson(json["notification"]),
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"notification": notification.toJson(),
"data": data.toJson(),
};
}
class Data {
Data({
this.productId,
this.page,
this.clickAction,
});
final String productId;
final String page;
final String clickAction;
factory Data.fromJson(Map<String, dynamic> json) => Data(
productId: json["productId"],
page: json["page"],
clickAction: json["click_action"],
);
Map<String, dynamic> toJson() => {
"productId": productId,
"page": page,
"click_action": clickAction,
};
}
class Notification {
Notification({
this.title,
this.body,
});
final String title;
final String body;
factory Notification.fromJson(Map<String, dynamic> json) => Notification(
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"title": title,
"body": body,
};
}
A function to build as
Future<NotificationMessage> getNotf() {
var parsedJson = json.decode(//your received object);
return NotificationMessage.fromJson(parsedJson);
}
Now you can receive this in a builder such as
_futureNotifications =Future<NotificationMessage>
_futureNotifications = getNotf(); //this is a function and can be used after a gesture or initState
FutureBuilder<NotificationMessage>(
future: _futureNotifications,
builder: (context, snapshot) {
}