Flutter converting custom stacked objects to json - json

So I have a relatively complex object structure and I want to save it in SQFLite. But since this object has list of other objects, I thought that I would convert the list of subobjects to json and save this as text.
Like this:
"name": "String",
"Body": {
"Object1": [
{
"index": int,
}
],
"Object2": [
{
"index":2,
}
]
}
When I press a button a new object is created and added to the database. (rawInsert)
But this problem arises:
Unhandled Exception: DatabaseException(java.lang.String cannot be cast to java.lang.Integer)
Which as far as I understand it means that there was an error converting a string to an int.
The full error code
E/flutter (20088): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: DatabaseException(java.lang.String cannot be cast to java.lang.Integer) sql 'INSERT Into workoutPlan (name,id,workoutDays,pastId,timesDone,workoutBody) VALUES (?,?,?,?,?,?)' args [nummero uno, 2, [Monday, Friday], 345, 45, {Pause: [{timeInMilSec: 900, index: 5}], exercise: [{goal: 2, weightGoal: [15, 15, 15], name: PushUp, timeGoal: 900, index: 1, repGoal: 3, setGoal: [infinity, 15, 3]}]}]}
My model class:
import 'dart:convert';
PlanModel planModelFromJson(String str) => PlanModel.fromJson(json.decode(str));
String planModelToJson(PlanModel data) => json.encode(data.toJson());
class PlanModel {
PlanModel({
this.name,
this.id,
this.workoutDays,
this.pastId,
this.timesDone,
this.workoutBody,
});
String name;
int id;
List<String> workoutDays;
int pastId;
int timesDone;
WorkoutBody workoutBody;
factory PlanModel.fromJson(Map<String, dynamic> json) => PlanModel(
name: json["name"],
id: json["id"],
workoutDays: List<String>.from(json["workoutDays"].map((x) => x)),
pastId: json["pastId"],
timesDone: json["timesDone"],
workoutBody: WorkoutBody.fromJson(json["workoutBody"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"id": id,
"workoutDays": List<dynamic>.from(workoutDays.map((x) => x)),
"pastId": pastId,
"timesDone": timesDone,
"workoutBody": workoutBody.toJson(),
};
}
class WorkoutBody {
WorkoutBody({
this.exercise,
this.pause,
});
List<Exercise> exercise;
List<Pause> pause;
factory WorkoutBody.fromJson(Map<String, dynamic> json) => WorkoutBody(
exercise: List<Exercise>.from(json["exercise"].map((x) => Exercise.fromJson(x))),
pause: List<Pause>.from(json["Pause"].map((x) => Pause.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"exercise": List<dynamic>.from(exercise.map((x) => x.toJson())),
"Pause": List<dynamic>.from(pause.map((x) => x.toJson())),
};
}
class Exercise {
Exercise({
this.index,
this.name,
this.goal,
this.repGoal,
this.weightGoal,
this.timeGoal,
this.setGoal,
});
int index;
String name;
int goal;
int repGoal;
List<int> weightGoal;
int timeGoal;
List<String> setGoal;
factory Exercise.fromJson(Map<String, dynamic> json) => Exercise(
index: json["index"],
name: json["name"],
goal: json["goal"],
repGoal: json["repGoal"],
weightGoal: List<int>.from(json["weightGoal"].map((x) => x)),
timeGoal: json["timeGoal"],
setGoal: List<String>.from(json["setGoal"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"index": index,
"name": name,
"goal": goal,
"repGoal": repGoal,
"weightGoal": List<dynamic>.from(weightGoal.map((x) => x)),
"timeGoal": timeGoal,
"setGoal": List<dynamic>.from(setGoal.map((x) => x)),
};
}
class Pause {
Pause({
this.index,
this.timeInMilSec,
});
int index;
int timeInMilSec;
factory Pause.fromJson(Map<String, dynamic> json) => Pause(
index: json["index"],
timeInMilSec: json["timeInMilSec"],
);
Map<String, dynamic> toJson() => {
"index": index,
"timeInMilSec": timeInMilSec,
};
}

I found the problem :)
In the planModel toJson() I had
"workoutDays": List<dynamic>.from(workoutDays.map((x) => x)),
and changed it to jsonDecode(workoutDays) and to read it again I used jsonEncode(src)

Flutter is probably getting your variable as a String.
To avoid any type problem I always do something like this:
int.tryParse(workoutBody.toString());
You should probably do this for all the stored data, especially when it comes to convert SQL query to dart int then json int.

Related

How to fetch a data from JSON in flutter?

I have a JSON file and i want to fetch the data.
here a small Json example, in this Example as we see the employee has 2 properties,
name and List of countries :
{
"Employee": [
{
"id":1
"name": "John",
"Countries": [
{
"id" :1
"country": "Uk"
},
{
"id" :2
"country": "USA"
},
{
"id" :3
"country": "Germany"
}
]
}
]
}
I used to use this method to fetch the data from JSON but the problem i faced is that this method works just with Json that doesnt have a list property :
Future<List<EmployeeModel>> fetchEmployeeList() async {
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var data = jsonDecode(response.body) as List;
print(data);
final employeeList = data.map((e) => EmployeeModel.fromJson(e)).toList();
return employeeList;
} else {
throw Exception("Failed to load ");
}
} catch (e) {
print(e);
rethrow;
}
}
here the model file :
import 'dart:convert';
List<EmployeeModel> employeeModelFromJson(String str) =>
List<EmployeeModel>.from(
json.decode(str).map((x) => EmployeeModel.fromJson(x)));
String employeeModelToJson(List<EmployeeModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class EmployeeModel {
EmployeeModel({
this.id,
this.name,
this.countries,
});
int id;
String name;
List<Country> countries;
factory EmployeeModel.fromJson(Map<String, dynamic> json) => EmployeeModel(
id: json["id"],
name: json["name"],
countries: List<Country>.from(
json["Countries"].map((x) => Country.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"Countries": List<dynamic>.from(countries.map((x) => x.toJson())),
};
}
class Country {
Country({
this.id,
this.country,
});
int id;
String country;
factory Country.fromJson(Map<String, dynamic> json) => Country(
id: json["id"],
country: json["country"],
);
Map<String, dynamic> toJson() => {
"id": id,
"country": country,
};
}
var data = jsonDecode(response.body);
print(data['Employee'][0]['Countries'][0]['country'];
//Output uk
Also consider creating a model for the json so you can parse it easily and don't have to write named keys.
https://docs.flutter.dev/development/data-and-backend/json
There are some online tools like quicktype.io too
EDIT
final employeeList = data.map((e) => EmployeeModel.fromJson(e)).toList();
print(employeeList[0].countries [0].country);
//Output uk

Convert JSON LIST String to JSON Object Flutter FormatException: Unexpected character (at character 2)

I am making a call to an endpoint that returns a string. How do I format the string to a model, The response is a list of object.
So, within my code, I map the formatted the response to look like
//response from server
[
{
"name" : "Test Test",
"age" : 10
},
{
"name" : "Test Test",
"age" : 10
}
]
But I formatted it to look as below
Map<String, dynamic> myResponse = {"status": true, "data": responseFromServer};
Response model = Response.fromJson(jsonDecode(result));
But I get the error as below
I/flutter ( 7718): FormatException: Unexpected character (at character 2)
I/flutter ( 7718): {status: true, data: [{"key":127,"name":"Statement 3!","clientFullName":nul...
I/flutter ( 7718): ^
Here is my model
// To parse this JSON data, do
//
// final response = responseFromJson(jsonString);
import 'dart:convert';
Response responseFromJson(String str) => Response.fromJson(json.decode(str));
String responseToJson(Response data) => json.encode(data.toJson());
class Response {
Response({
this.status,
this.data,
});
bool status;
List<Datum> data;
factory Response.fromJson(Map<String, dynamic> json) => Response(
status: json["status"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.name,
this.age,
});
String name;
int age;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
name: json["name"],
age: json["age"],
);
Map<String, dynamic> toJson() => {
"name": name,
"age": age,
};
}
What I am trying to achieve is to pass the response to a Model and return the model to the used. What am I doing wrong?
Two things here:
Please share the code of CustomModel to evaluate further.
Use this simple tool to create JSON to dart class in and integrate in seconds.

parsing complex json flutter list<map> in list

I have a json response where there is a list that contains a list, then there is a map in it, I tried to parse it but it failed, what kind of error did I do? Previously I used this method to parse the map that was in the list and it worked
response json
{
"status": "success",
"data": [
{
"id_category": 1,
"category_slug": "cc",
"category_name": "Credit Card",
"data_payment": [
{
"payment_slug": "cc",
"payment_name": "Credit Card",
"payment_logo": "https://cdn.xx.id/assets_midtrans/cc.png"
}
]
}
],
"message": "Success Get Data"
}
mycode
class PaymentMethodListModel {
final String status, message;
final List<_Data> data;
PaymentMethodListModel({
this.status,
this.message,
this.data,
});
factory PaymentMethodListModel.fromJson(Map<String, dynamic> x) {
var list = x['data'] as List;
print(list.runtimeType);
List<_Data> sd = list.map((i) => _Data.fromJson(i)).toList();
return PaymentMethodListModel(
status: x['status'],
data: sd,
message: x['message'],
);
}
}
class _Data {
final String categorySlug, categoryName;
final List<DataPayment> dataPayment;
_Data({
this.categorySlug,
this.categoryName,
this.dataPayment,
});
factory _Data.fromJson(Map<String, dynamic> obj) {
var list = obj['data_payment'] as List;
List<DataPayment> dataPaymentList = list.map((i) => DataPayment.fromJson(i)).toList();
return _Data(
categorySlug: obj['category_slug'],
categoryName: obj['category_name'],
dataPayment: dataPaymentList,
);
}
}
class DataPayment {
final String paymentSlug, paymentName, paymentLogo;
DataPayment({
this.paymentSlug,
this.paymentName,
this.paymentLogo,
});
factory DataPayment.fromJson(Map<String, dynamic> x) => DataPayment(
paymentSlug: x['payment_slug'],
paymentName: x['payment_name'],
paymentLogo: x['payment_logo'],
);
}
error message
The method 'map' was called on null.
Receiver: null
Tried calling: map(Closure: (dynamic) => DataPayment)
Try below code
var paymentListModel = PaymentListModel.fromJson(json.decode(str));
class PaymentListModel {
PaymentListModel({
this.status,
this.data,
this.message,
});
String status;
List<Datum> data;
String message;
factory PaymentListModel.fromJson(Map<String, dynamic> json) => PaymentListModel(
status: json["status"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
message: json["message"],
);
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"message": message,
};
}
class Datum {
Datum({
this.idCategory,
this.categorySlug,
this.categoryName,
this.dataPayment,
});
int idCategory;
String categorySlug;
String categoryName;
List<DataPayment> dataPayment;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
idCategory: json["id_category"],
categorySlug: json["category_slug"],
categoryName: json["category_name"],
dataPayment: List<DataPayment>.from(json["data_payment"].map((x) => DataPayment.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id_category": idCategory,
"category_slug": categorySlug,
"category_name": categoryName,
"data_payment": List<dynamic>.from(dataPayment.map((x) => x.toJson())),
};
}
class DataPayment {
DataPayment({
this.paymentSlug,
this.paymentName,
this.paymentLogo,
});
String paymentSlug;
String paymentName;
String paymentLogo;
factory DataPayment.fromJson(Map<String, dynamic> json) => DataPayment(
paymentSlug: json["payment_slug"],
paymentName: json["payment_name"],
paymentLogo: json["payment_logo"],
);
Map<String, dynamic> toJson() => {
"payment_slug": paymentSlug,
"payment_name": paymentName,
"payment_logo": paymentLogo,
};
}

Dart issue with getting JSON data

I'm trying to get data from JSON, the data is as follows :
For the JSON above, I've generated a Dart Class using this website
the code below works fine with this response : RESPONSE TVSHOW DETAILS, I can see all data loaded successfully in my app, but not with this one RESPONSE TVSHOW DETAILS 2, nothing is loaded
TVShow tvShowFromJson(String str) => TVShow.fromJson(json.decode(str));
String tvShowToJson(TVShow data) => json.encode(data.toJson());
class TVShow {
String backdropPath;
List<CreatedBy> createdBy;
List<int> episodeRunTime;
DateTime firstAirDate;
List<Genre> genres;
String homepage;
int id;
bool inProduction;
List<String> languages;
DateTime lastAirDate;
TEpisodeToAir lastEpisodeToAir;
String name;
TEpisodeToAir nextEpisodeToAir;
List<Network> networks;
int numberOfEpisodes;
int numberOfSeasons;
List<String> originCountry;
String originalLanguage;
String originalName;
String overview;
double popularity;
String posterPath;
List<Network> productionCompanies;
List<Season> seasons;
String status;
String type;
double voteAverage;
int voteCount;
TVShow({
this.backdropPath,
this.createdBy,
this.episodeRunTime,
this.firstAirDate,
this.genres,
this.homepage,
this.id,
this.inProduction,
this.languages,
this.lastAirDate,
this.lastEpisodeToAir,
this.name,
this.nextEpisodeToAir,
this.networks,
this.numberOfEpisodes,
this.numberOfSeasons,
this.originCountry,
this.originalLanguage,
this.originalName,
this.overview,
this.popularity,
this.posterPath,
this.productionCompanies,
this.seasons,
this.status,
this.type,
this.voteAverage,
this.voteCount,
});
factory TVShow.fromJson(Map<String, dynamic> json) => TVShow(
backdropPath: json["backdrop_path"],
createdBy: List<CreatedBy>.from(json["created_by"].map((x) => CreatedBy.fromJson(x))),
episodeRunTime: List<int>.from(json["episode_run_time"].map((x) => x)),
firstAirDate: DateTime.parse(json["first_air_date"]),
genres: List<Genre>.from(json["genres"].map((x) => Genre.fromJson(x))),
homepage: json["homepage"],
id: json["id"],
inProduction: json["in_production"],
languages: List<String>.from(json["languages"].map((x) => x)),
lastAirDate: DateTime.parse(json["last_air_date"]),
lastEpisodeToAir: TEpisodeToAir.fromJson(json["last_episode_to_air"]),
name: json["name"],
nextEpisodeToAir: TEpisodeToAir.fromJson(json["next_episode_to_air"]),
networks: List<Network>.from(json["networks"].map((x) => Network.fromJson(x))),
numberOfEpisodes: json["number_of_episodes"],
numberOfSeasons: json["number_of_seasons"],
originCountry: List<String>.from(json["origin_country"].map((x) => x)),
originalLanguage: json["original_language"],
originalName: json["original_name"],
overview: json["overview"],
popularity: json["popularity"].toDouble(),
posterPath: json["poster_path"],
productionCompanies: List<Network>.from(json["production_companies"].map((x) => Network.fromJson(x))),
seasons: List<Season>.from(json["seasons"].map((x) => Season.fromJson(x))),
status: json["status"],
type: json["type"],
voteAverage: json["vote_average"].toDouble(),
voteCount: json["vote_count"],
);
Map<String, dynamic> toJson() => {
"backdrop_path": backdropPath,
"created_by": List<dynamic>.from(createdBy.map((x) => x.toJson())),
"episode_run_time": List<dynamic>.from(episodeRunTime.map((x) => x)),
"first_air_date":
"${firstAirDate.year.toString().padLeft(4, '0')}-${firstAirDate.month.toString().padLeft(2, '0')}-${firstAirDate.day.toString().padLeft(2, '0')}",
"genres": List<dynamic>.from(genres.map((x) => x.toJson())),
"homepage": homepage,
"id": id,
"in_production": inProduction,
"languages": List<dynamic>.from(languages.map((x) => x)),
"last_air_date":
"${lastAirDate.year.toString().padLeft(4, '0')}-${lastAirDate.month.toString().padLeft(2, '0')}-${lastAirDate.day.toString().padLeft(2, '0')}",
"last_episode_to_air": lastEpisodeToAir.toJson(),
"name": name,
"next_episode_to_air": nextEpisodeToAir.toJson(),
"networks": List<dynamic>.from(networks.map((x) => x.toJson())),
"number_of_episodes": numberOfEpisodes,
"number_of_seasons": numberOfSeasons,
"origin_country": List<dynamic>.from(originCountry.map((x) => x)),
"original_language": originalLanguage,
"original_name": originalName,
"overview": overview,
"popularity": popularity,
"poster_path": posterPath,
"production_companies": List<dynamic>.from(productionCompanies.map((x) => x.toJson())),
"seasons": List<dynamic>.from(seasons.map((x) => x.toJson())),
"status": status,
"type": type,
"vote_average": voteAverage,
"vote_count": voteCount,
};
}
class CreatedBy {
int id;
String creditId;
String name;
int gender;
String profilePath;
CreatedBy({
this.id,
this.creditId,
this.name,
this.gender,
this.profilePath,
});
factory CreatedBy.fromJson(Map<String, dynamic> json) => CreatedBy(
id: json["id"],
creditId: json["credit_id"],
name: json["name"],
gender: json["gender"],
profilePath: json["profile_path"],
);
Map<String, dynamic> toJson() => {
"id": id,
"credit_id": creditId,
"name": name,
"gender": gender,
"profile_path": profilePath,
};
}
class Genre {
int id;
String name;
Genre({
this.id,
this.name,
});
factory Genre.fromJson(Map<String, dynamic> json) => Genre(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
class TEpisodeToAir {
DateTime airDate;
int episodeNumber;
int id;
String name;
String overview;
String productionCode;
int seasonNumber;
int showId;
String stillPath;
double voteAverage;
int voteCount;
TEpisodeToAir({
this.airDate,
this.episodeNumber,
this.id,
this.name,
this.overview,
this.productionCode,
this.seasonNumber,
this.showId,
this.stillPath,
this.voteAverage,
this.voteCount,
});
factory TEpisodeToAir.fromJson(Map<String, dynamic> json) => TEpisodeToAir(
airDate: DateTime.parse(json["air_date"]),
episodeNumber: json["episode_number"],
id: json["id"],
name: json["name"],
overview: json["overview"],
productionCode: json["production_code"],
seasonNumber: json["season_number"],
showId: json["show_id"],
stillPath: json["still_path"],
voteAverage: json["vote_average"].toDouble(),
voteCount: json["vote_count"],
);
Map<String, dynamic> toJson() => {
"air_date":
"${airDate.year.toString().padLeft(4, '0')}-${airDate.month.toString().padLeft(2, '0')}-${airDate.day.toString().padLeft(2, '0')}",
"episode_number": episodeNumber,
"id": id,
"name": name,
"overview": overview,
"production_code": productionCode,
"season_number": seasonNumber,
"show_id": showId,
"still_path": stillPath,
"vote_average": voteAverage,
"vote_count": voteCount,
};
}
class Network {
String name;
int id;
String logoPath;
String originCountry;
Network({
this.name,
this.id,
this.logoPath,
this.originCountry,
});
factory Network.fromJson(Map<String, dynamic> json) => Network(
name: json["name"],
id: json["id"],
logoPath: json["logo_path"] == null ? null : json["logo_path"],
originCountry: json["origin_country"],
);
Map<String, dynamic> toJson() => {
"name": name,
"id": id,
"logo_path": logoPath == null ? null : logoPath,
"origin_country": originCountry,
};
}
class Season {
DateTime airDate;
int episodeCount;
int id;
String name;
String overview;
String posterPath;
int seasonNumber;
Season({
this.airDate,
this.episodeCount,
this.id,
this.name,
this.overview,
this.posterPath,
this.seasonNumber,
});
factory Season.fromJson(Map<String, dynamic> json) => Season(
airDate: DateTime.parse(json["air_date"]),
episodeCount: json["episode_count"],
id: json["id"],
name: json["name"],
overview: json["overview"],
posterPath: json["poster_path"],
seasonNumber: json["season_number"],
);
Map<String, dynamic> toJson() => {
"air_date":
"${airDate.year.toString().padLeft(4, '0')}-${airDate.month.toString().padLeft(2, '0')}-${airDate.day.toString().padLeft(2, '0')}",
"episode_count": episodeCount,
"id": id,
"name": name,
"overview": overview,
"poster_path": posterPath,
"season_number": seasonNumber,
};
}
When I tried to catch the error with :
if (snapshot.hasError) {
print('ERROR : ${snapshot.error}');
}
I got this :
I/flutter (16719): ERROR : NoSuchMethodError: The method '[]' was
called on null. I/flutter (16719): Receiver: null I/flutter (16719):
Tried calling: []("air_date")
It could be because the "next_episode_to_air" parameter in the second link (TV show details 2) is actually a null value! You can check for nulls using ?? operator in Dart.
You can have a look at its usage here
In your case, you could use it like this in your TVShow.fromJson method,
nextEpisodeToAir: TEpisodeToAir.fromJson(json["next_episode_to_air"] ?? <your-default-value>),
This will check your code for the value of json["next_episode_to_air"] and put an your default value at it's place if it turns out to be null. You can then deal with this default (or maybe null) value accordingly in your code later.
I have solved the issue with null case handling.In 2nd response, response with key next_episode_to_air is null. Due to this getting error, accessing key on null.
Just handle the possible case for data, currently at factory TVShow.fromJson i.e.
nextEpisodeToAir: json["next_episode_to_air"] == null ? null : TEpisodeToAir.fromJson(json["next_episode_to_air"])

NoSuchMethodError: The method 'map' was called on null

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter (19718): Receiver: null
E/flutter (19718): Tried calling: map(Closure: (dynamic) => SeriesNo)
I tried json_annotation and json Serieizable but don't work.According my model one.json is ok.but two.json is reques error happen as title.How to solve.I known series no is error but i have no idea how to solve.
This is one.json
{
"bookDetail": {
"title": "aaa",
"author": "aaa",
"image": "https://",
"text": "aaa",
"series_no": [
{
"id": 2
}
],
"created_at": "2019-08-27 15:19:10"
}
}
This is two.json
{
"bookDetail": {
"title": "Test",
"author": "TEst",
"image": "https:/riv19q9x.png",
"text": "Test",
"series_no": null,
"created_at": "2019-08-27 15:13:56"
}
}
This is detail.model using bloc flutter
class BookDetailModel {
BookDetail bookDetail;
BookDetailModel({
this.bookDetail,
});
factory BookDetailModel.fromJson(Map<String, dynamic> json) =>
new BookDetailModel(
bookDetail: BookDetail.fromJson(json["bookDetail"]),
);
Map<String, dynamic> toJson() => {
"bookDetail": bookDetail.toJson(),
};
}
#JsonSerializable(nullable: true)
class BookDetail {
String title;
String author;
String image;
String text;
List<SeriesNo> seriesNo;
DateTime createdAt;
BookDetail({
this.title,
this.author,
this.image,
this.text,
this.seriesNo,
this.createdAt,
});
factory BookDetail.fromJson(Map<String, dynamic> json) => new BookDetail(
title: json["title"],
author: json["author"],
image: json["image"],
text: json["text"],
seriesNo: new List<SeriesNo>.from(
json["series_no"].map((x) => SeriesNo.fromJson(x))),
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"author": author,
"image": image,
"text": text,
"series_no": new List<dynamic>.from(seriesNo.map((x) => x.toJson())),
"created_at": createdAt.toIso8601String(),
};
}
#JsonSerializable(nullable: true)
class SeriesNo {
int id;
SeriesNo({
this.id,
});
factory SeriesNo.fromJson(Map<String, dynamic> json) => new SeriesNo(
id: json["id"],
);
Map<String, dynamic> toJson() => {
"id": id,
};
}
Try to verify if is not null before:
seriesNo: json["series_no"] != null ? new List<SeriesNo>.from( json["series_no"].map((x) => SeriesNo.fromJson(x))) : List<SeriesNo>().
This is answer for my question.Crd #Stel
try placing seriesNo as dynamic and placing the remaining fields
class BookDetailModel {
BookDetail bookDetail;
BookDetailModel({
this.bookDetail,
});
factory BookDetailModel.fromJson(Map<String, dynamic> json) => BookDetailModel(
bookDetail: BookDetail.fromJson(json["bookDetail"]),
);
Map<String, dynamic> toJson() => {
"bookDetail": bookDetail.toJson(),
};
}
class BookDetail {
String title;
String author;
String image;
String text;
dynamic seriesNo;
DateTime createdAt;
BookDetail({
this.title,
this.author,
this.image,
this.text,
this.seriesNo,
this.createdAt,
});
factory BookDetail.fromJson(Map<String, dynamic> json) => BookDetail(
title: json["title"],
author: json["author"],
image: json["image"],
text: json["text"],
seriesNo: json["series_no"],
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"author": author,
"image": image,
"text": text,
"series_no": seriesNo,
"created_at": createdAt.toIso8601String(),
};
}
If it's a List and a double value, how can it be written even if it's correct? I got this problem. Please see my link.Link Linkclass
Food _$FoodFromJson(Map<String, dynamic> json) => Food(
ingredient: (json['ingredient'] as List<dynamic>)
.map((e) => e as String)
.toList(),
quantity:
(json['quantity'] as List<dynamic>).map((e) => e as String).toList(),
uom: (json['uom'] as List<dynamic>).map((e) => e as String).toList(),
step: (json['step'] as List<dynamic>).map((e) => e as String).toList(),
);