Related
I am trying to convert JSON response to dart but over 3 error. I convert the Json from online website https://javiercbk.github.io/json_to_dart/
the errors says : The method 'toJson' isn't defined for the type 'List'.
Try correcting the name to the name of an existing method, or defining a method named 'toJson'.
the code :
class RedZoneModel {
bool? status;
List<Data>? data;
RedZoneModel({this.status, this.data});
RedZoneModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) { data!.add(new Data.fromJson(v)); });
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
int? id;
String? areaName;
Geojson? geojson;
String? createdAt;
String? updatedAt;
Data({this.id, this.areaName, this.geojson, this.createdAt, this.updatedAt});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
areaName = json['area_name'];
geojson = json['geojson'] != null ? new Geojson.fromJson(json['geojson']) : null;
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['area_name'] = this.areaName;
if (this.geojson != null) {
data['geojson'] = this.geojson!.toJson();
}
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Geojson {
String? type;
List<List>? coordinates;
Geojson({this.type, this.coordinates});
Geojson.fromJson(Map<String, dynamic> json) {
type = json['type'];
if (json['coordinates'] != null) {
coordinates = <List>[];
json['coordinates'].forEach((v) { coordinates!.add(new List.fromJson(v)); }); // ! Error at List.fromJson(v)
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
if (this.coordinates != null) {
data['coordinates'] = this.coordinates!.map((v) => v.toJson()).toList(); // ! Error at v.toJson()
}
return data;
}
}
class Coordinates {
Coordinates({ }); // ! Error at Coordinates({ });
Coordinates.fromJson(Map<String, dynamic> json) {
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
return data;
}
}
and this is the response :
{
"status": true,
"data": [
{
"id": 8,
"area_name": "Surian",
"geojson": {
"type": "Polygon",
"coordinates": [
[
[
-1.2453052,
460.8429751
],
[
-1.2200768,
460.9066456
],
[
-1.2564606,
460.9423423
],
[
-1.2940451,
460.8711205
],
[
-1.2453052,
460.8429751
],
[
-1.2940451,
460.8711205
],
[
-1.2453052,
460.8429751
]
]
]
},
"created_at": "2022-08-29T14:30:10.000000Z",
"updated_at": "2022-12-19T18:30:10.000000Z"
},
{
"id": 13,
"area_name": "test edit",
"geojson": {
"type": "Polygon",
"coordinates": [
[
[
123,
123
],
[
123,
123
],
[
123,
123
],
[
123,
123
],
[
123,
123
]
]
]
},
"created_at": "2022-08-29T15:43:35.000000Z",
"updated_at": "2022-12-20T08:28:00.000000Z"
}
]
}
Anyone have any suggestion?
You shouldn't really use online generators that convert JSON to Dart objects.
Instead, learn about json and serialization. You can use dart packages such as freezed and json_serializable to generate the encoding boilerplate for your JSON response.
Here is sample json to Dart object converter for your json response above:
class Data {
const Data({
required this.id,
required this.area_name,
required this.geojson,
required this.created_at,
required this.updated_at,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json['id'] as int,
area_name: json['area_name'] as String,
geojson: GeoJson.fromJson(json['geojson'] as Map<String, dynamic>),
created_at: DateTime.parse(json['created_at'] as String),
updated_at: DateTime.parse(json['updated_at'] as String),
);
final int id;
final String area_name;
final GeoJson geojson;
final DateTime created_at;
final DateTime updated_at;
}
class GeoJson {
const GeoJson({
required this.type,
required this.coordinates,
});
factory GeoJson.fromJson(Map<String, dynamic> json) => GeoJson(
type: json['type'] as String,
coordinates: (json['coordinates'] as List<dynamic>)
.map((e) => Polygon.fromJson(e as Map<String, dynamic>))
.toList(),
);
final String type;
final List<Polygon> coordinates;
}
class Polygon {
const Polygon({
required this.lat,
required this.lang,
});
/// Creates a Polygon from Json map
factory Polygon.fromJson(Map<String, dynamic> json) => Polygon(
lat: json['lat'] as num,
lang: json['lang'] as num,
);
final num lat;
final num lang;
}
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
I got this problem when trying to serialize complex JSON that i fetch from the internet using json_serializable and using FutureProvider to connect them together. This is the json file,
{
"data": {
"quiz": {
"stats": {
"played": 6691,
"totalPlayers": "29553"
},
"publishedVersion": "5a13431202b92110003fdb92",
"_id": "5a133e2302b92110003fd8ef",
"createdBy": {
"local": {
"username": "jshutt"
},
"occupation": "teacher_school"
}, //createdBy
"info": {
"name": "Proportional Relationships",
"image": "https://quizizz.com/media/resource/gs/quizizz-media/quizzes/L2FwcGhvc3RpbmdfcHJvZC9ibG9icy9BRW5CMlVyNUFUSlN0VXhVSzcxY1hHZGN4UmJYVEdiWHRpeXBCcmVvQXhwT0JhckZwdnhBdkw4cHFqYjNVNktJSnlwSEdtUlJubV9Nc2Qxck51Z2Z5ampNSzJWb09Qek1tU0Joc0NaSUZtdGNyYzlQN1ZUQWREQS5EOUxuUGh3MUxaZzk0MUYz",
"subjects": [
"Mathematics"
],
"topics": [
"Pre-algebra"
],
"subtopics": [
"Proportional relationships",
"Constant of Proportionality",
"proportional graphs",
"proportion equations"
],
"questions": [
{
"structure": {
"kind": "MCQ",
"query": {
"media": [
{
"url": "https://quizizz.com/media/resource/gs/quizizz-media/questions/L2FwcGhvc3RpbmdfcHJvZC9ibG9icy9BRW5CMlVwajVWZnl0S2RBRXpIazROejFaSTl0dkU3Rmt6cjhtcTRvTGVxeFJzeHVLQzlZa3hzYjNZdkpNa3N1TTItaE5UNmVHUUZVdl9ZdTR6YnNaTk5hV0luZWhZQm9sUS5pOTBwLU1YLUtMRXR5YlBZ"
}
], //media
"text": "Write an equation for this relationship.",
}, //query
"options": [
{
"text": "y=1/5x"
},
{
"text": "y=1/2x"
},
{
"text": "y=2x"
},
{
"text": "y=5x"
}
], //options
"answer": 3
}
}
]
}
}
This is the code that contain the class for the serialization,
import 'package:json_annotation/json_annotation.dart';
import 'questions_data/questions_quiz.dart';
part 'questions.g.dart';
#JsonSerializable(explicitToJson: true)
class CoreData {
QuestionData data;
CoreData({this.data});
factory CoreData.fromJson(Map<String, dynamic> json) => _$CoreDataFromJson(json);
Map<String, dynamic> toJson() => _$CoreDataToJson(this);
}
#JsonSerializable(explicitToJson: true)
class QuestionData {
Quiz quiz;
QuestionData({this.quiz});
factory QuestionData.fromJson(Map<String, dynamic> json) => _$QuestionDataFromJson(json);
Map<String, dynamic> toJson() => _$QuestionDataToJson(this);
}
#JsonSerializable(explicitToJson: true)
class QuestionsList {
List<Questions> questions;
QuestionsList({this.questions});
factory QuestionsList.fromJson(Map<String, dynamic> json) => _$QuestionsListFromJson(json);
Map<String, dynamic> toJson() => _$QuestionsListToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Questions {
Structure structure;
Questions({this.structure});
factory Questions.fromJson(Map<String, dynamic> json) => _$QuestionsFromJson(json);
Map<String, dynamic> toJson() => _$QuestionsToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Structure {
String kind;
Query query;
Options options;
int answer;
Structure({this.kind, this.query, this.options, this.answer});
factory Structure.fromJson(Map<String, dynamic> json) => _$StructureFromJson(json);
Map<String, dynamic> toJson() => _$StructureToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Quiz {
String publishedVersion;
#JsonKey(name: '_id')
String id;
Stats stats;
CreatedBy createdBy;
Info info;
Quiz({this.publishedVersion, this.id, this.stats, this.createdBy, this.info});
factory Quiz.fromJson(Map<String, dynamic> json) => _$QuizFromJson(json);
Map<String, dynamic> toJson() => _$QuizToJson(this);
}
#JsonSerializable(explicitToJson: true)
class CreatedBy {
Local local;
String occupation;
CreatedBy({this.local, this.occupation});
factory CreatedBy.fromJson(Map<String, dynamic> json) => _$CreatedByFromJson(json);
Map<String, dynamic> toJson() => _$CreatedByToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Local {
String username;
Local({this.username});
factory Local.fromJson(Map<String, dynamic> json) => _$LocalFromJson(json);
Map<String, dynamic> toJson() => _$LocalToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Stats {
int played;
int totalPlayers;
Stats({this.played, this.totalPlayers});
factory Stats.fromJson(Map<String, dynamic> json) => _$StatsFromJson(json);
Map<String, dynamic> toJson() => _$StatsToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Info {
String name;
String image;
List<String> subjects, topics, subtopics;
Questions questions;
Info({
this.name,
this.image,
this.subjects,
this.topics,
this.subtopics,
this.questions});
factory Info.fromJson(Map<String, dynamic> json) => _$InfoFromJson(json);
Map<String, dynamic> toJson() => _$InfoToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Query {
String text;
List<Images> media;
Query({this.text, this.media});
factory Query.fromJson(Map<String, dynamic> json) => _$QueryFromJson(json);
Map<String, dynamic> toJson() => _$QueryToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Images {
String url;
Images({this.url});
factory Images.fromJson(Map<String, dynamic> json) => _$ImagesFromJson(json);
Map<String, dynamic> toJson() => _$ImagesToJson(this);
}
#JsonSerializable(explicitToJson: true)
class Options {
List<QuestionText> options;
Options ({this.options});
factory Options.fromJson(Map<String, dynamic> json) => _$OptionsFromJson(json);
Map<String, dynamic> toJson() => _$OptionsToJson(this);
}
#JsonSerializable(explicitToJson: true)
class QuestionText {
String text;
QuestionText({this.text});
factory QuestionText.fromJson(Map<String, dynamic> json) => _$QuestionTextFromJson(json);
Map<String, dynamic> toJson() => _$QuestionTextToJson(this);
}
The future provider to fetch the json file and convert it to dart,
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'package:quizizz_cheat/models/questions.dart';
class QuestionsService {
Future<CoreData> fetchQuestion() async {
final response = await http.get(url);
var jsonResponse = convert.jsonDecode(response.body);
CoreData parsedQuestions = CoreData.fromJson(jsonResponse);
return parsedQuestions;
}
}
This is the genearted code,
part of 'questions.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CoreData _$CoreDataFromJson(Map<String, dynamic> json) {
return CoreData(
data: json['data'] == null
? null
: QuestionData.fromJson(json['data'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$CoreDataToJson(CoreData instance) => <String, dynamic>{
'data': instance.data?.toJson(),
};
QuestionData _$QuestionDataFromJson(Map<String, dynamic> json) {
return QuestionData(
quiz: json['quiz'] == null
? null
: Quiz.fromJson(json['quiz'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$QuestionDataToJson(QuestionData instance) =>
<String, dynamic>{
'quiz': instance.quiz?.toJson(),
};
QuestionsList _$QuestionsListFromJson(Map<String, dynamic> json) {
return QuestionsList(
questions: (json['questions'] as List)
?.map((e) =>
e == null ? null : Questions.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$QuestionsListToJson(QuestionsList instance) =>
<String, dynamic>{
'questions': instance.questions?.map((e) => e?.toJson())?.toList(),
};
Questions _$QuestionsFromJson(Map<String, dynamic> json) {
return Questions(
structure: json['structure'] == null
? null
: Structure.fromJson(json['structure'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$QuestionsToJson(Questions instance) => <String, dynamic>{
'structure': instance.structure?.toJson(),
};
Structure _$StructureFromJson(Map<String, dynamic> json) {
return Structure(
kind: json['kind'] as String,
query: json['query'] == null
? null
: Query.fromJson(json['query'] as Map<String, dynamic>),
options: json['options'] == null
? null
: Options.fromJson(json['options'] as Map<String, dynamic>),
answer: json['answer'] as int,
);
}
Map<String, dynamic> _$StructureToJson(Structure instance) => <String, dynamic>{
'kind': instance.kind,
'query': instance.query?.toJson(),
'options': instance.options?.toJson(),
'answer': instance.answer,
};
Quiz _$QuizFromJson(Map<String, dynamic> json) {
return Quiz(
publishedVersion: json['publishedVersion'] as String,
id: json['_id'] as String,
stats: json['stats'] == null
? null
: Stats.fromJson(json['stats'] as Map<String, dynamic>),
createdBy: json['createdBy'] == null
? null
: CreatedBy.fromJson(json['createdBy'] as Map<String, dynamic>),
info: json['info'] == null
? null
: Info.fromJson(json['info'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$QuizToJson(Quiz instance) => <String, dynamic>{
'publishedVersion': instance.publishedVersion,
'_id': instance.id,
'stats': instance.stats?.toJson(),
'createdBy': instance.createdBy?.toJson(),
'info': instance.info?.toJson(),
};
CreatedBy _$CreatedByFromJson(Map<String, dynamic> json) {
return CreatedBy(
local: json['local'] == null
? null
: Local.fromJson(json['local'] as Map<String, dynamic>),
occupation: json['occupation'] as String,
);
}
Map<String, dynamic> _$CreatedByToJson(CreatedBy instance) => <String, dynamic>{
'local': instance.local?.toJson(),
'occupation': instance.occupation,
};
Local _$LocalFromJson(Map<String, dynamic> json) {
return Local(
username: json['username'] as String,
);
}
Map<String, dynamic> _$LocalToJson(Local instance) => <String, dynamic>{
'username': instance.username,
};
Stats _$StatsFromJson(Map<String, dynamic> json) {
return Stats(
played: json['played'] as int,
totalPlayers: json['totalPlayers'] as int,
);
}
Map<String, dynamic> _$StatsToJson(Stats instance) => <String, dynamic>{
'played': instance.played,
'totalPlayers': instance.totalPlayers,
};
Info _$InfoFromJson(Map<String, dynamic> json) {
return Info(
name: json['name'] as String,
image: json['image'] as String,
subjects: (json['subjects'] as List)?.map((e) => e as String)?.toList(),
topics: (json['topics'] as List)?.map((e) => e as String)?.toList(),
subtopics: (json['subtopics'] as List)?.map((e) => e as String)?.toList(),
questions: json['questions'] == null
? null
: Questions.fromJson(json['questions'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$InfoToJson(Info instance) => <String, dynamic>{
'name': instance.name,
'image': instance.image,
'subjects': instance.subjects,
'topics': instance.topics,
'subtopics': instance.subtopics,
'questions': instance.questions?.toJson(),
};
Query _$QueryFromJson(Map<String, dynamic> json) {
return Query(
text: json['text'] as String,
media: (json['media'] as List)
?.map((e) =>
e == null ? null : Images.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$QueryToJson(Query instance) => <String, dynamic>{
'text': instance.text,
'media': instance.media?.map((e) => e?.toJson())?.toList(),
};
Images _$ImagesFromJson(Map<String, dynamic> json) {
return Images(
url: json['url'] as String,
);
}
Map<String, dynamic> _$ImagesToJson(Images instance) => <String, dynamic>{
'url': instance.url,
};
Options _$OptionsFromJson(Map<String, dynamic> json) {
return Options(
options: (json['options'] as List)
?.map((e) =>
e == null ? null : QuestionText.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$OptionsToJson(Options instance) => <String, dynamic>{
'options': instance.options?.map((e) => e?.toJson())?.toList(),
};
QuestionText _$QuestionTextFromJson(Map<String, dynamic> json) {
return QuestionText(
text: json['text'] as String,
);
}
Map<String, dynamic> _$QuestionTextToJson(QuestionText instance) =>
<String, dynamic>{
'text': instance.text,
};
and this is the code where the converted json file shows up
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:quiz/screens/home.dart';
import 'package:quiz/services/questions_service.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final QuestionsService questionsService = QuestionsService();
#override
Widget build(BuildContext context) {
return FutureProvider(
create: (context) async => questionsService.fetchQuestion(),
catchError: (context, error) {
print(error.toString());
},
child: MaterialApp(
title: 'Quizizz cheat',
home: HomePage(),
),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
var question = Provider.of<CoreData>(context);
return Scaffold(
appBar: AppBar(
title: Text('Quizizz Cheat'),
),
body: question == null
? Center(child: CircularProgressIndicator())
: Center(
child: Text(question.data.quiz.info.questions.structure.kind),
),
);
}
}
When i try to run the project i got this error
I/flutter (23347): type 'List' is not a subtype of type
'Map<String, dynamic>' in type cast
I believe the problem comes from this code that trying to convert a json containing list of maps and the code that contain the json serialization method
#JsonSerializable(explicitToJson: true)
class QuestionsList {
List<Questions> questions;
QuestionsList({this.questions});
factory QuestionsList.fromJson(Map<String, dynamic> json) => _$QuestionsListFromJson(json);
Map<String, dynamic> toJson() => _$QuestionsListToJson(this);
}
I already fixed the problem, it seems that i need to be more careful at writing my code. The answer was simple, i need to change the type from this...
#JsonSerializable(explicitToJson: true)
class Info {
String name;
String image;
List<String> subjects, topics, subtopics;
Questions questions;
Info({
this.name,
this.image,
this.subjects,
this.topics,
this.subtopics,
this.questions});
factory Info.fromJson(Map<String, dynamic> json) => _$InfoFromJson(json);
Map<String, dynamic> toJson() => _$InfoToJson(this);
}
to this...
#JsonSerializable(explicitToJson: true)
class Info {
String name;
String image;
List<String> subjects, topics, subtopics;
List<Questions> questions;
Info({
this.name,
this.image,
this.subjects,
this.topics,
this.subtopics,
this.questions});
factory Info.fromJson(Map<String, dynamic> json) => _$InfoFromJson(json);
Map<String, dynamic> toJson() => _$InfoToJson(this);
}
and from this...
#JsonSerializable(explicitToJson: true)
class Structure {
String kind;
Query query;
Options options;
int answer;
Structure({this.kind, this.query, this.options, this.answer});
factory Structure.fromJson(Map<String, dynamic> json) => _$StructureFromJson(json);
Map<String, dynamic> toJson() => _$StructureToJson(this);
}
to this...
#JsonSerializable(explicitToJson: true)
class Structure {
String kind;
Query query;
List<QuestionText> options;
int answer;
Structure({this.kind, this.query, this.options, this.answer});
factory Structure.fromJson(Map<String, dynamic> json) => _$StructureFromJson(json);
Map<String, dynamic> toJson() => _$StructureToJson(this);
}
I'm receiving an Error following the Json Deserialisation cookbook
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
Bundle Class
class Bundle {
String resourceType;
String id;
String type;
int total;
List<Link> link;
List<Entry> entry;
Bundle(
{this.resourceType,
this.id,
this.type,
this.total,
this.link,
this.entry});
factory Bundle.fromJson(Map<String, dynamic> json) {
return Bundle(
resourceType : json['resourceType'],
id : json['id'],
type : json['type'],
total : json['total'],
);
}
Code:
try {
await parsePerson(resultString);
} catch (e) {
print('Bundlelist Error: $e');
}
Future<List<Bundle>> parsePerson(String body) async {
List<Bundle> bundleList = [];
try {
final parsed = json.decode(body);
bundleList = parsed.map<Bundle>((json) => Bundle.fromJson(json)).toList;
} catch (e) {
print('FutureError: $e');
}
return bundleList;
}
My Result string (partial): Full json is here.
{"resourceType":"Bundle","id":"f26779b4-5c3c-4c52-83b4-c689516a6a08","type":"searchset","link":[{"relation":"self","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?name=b\u0026_count=20"},{"relation":"next","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?-pageContext=7018d2bc-6be4-48e1-b8a4-a40f4e98c98c\u0026-pageDirection=NEXT"}],"entry":[{"fullUrl":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient/6160015","resource":{"resourceType":"Patient","id":"6160015","meta":{"versionId":"0","lastUpdated":"2019-07-08T20:37:03.000Z"},"text":{"status":"generated","div":"\u003Cdiv\u003E\u003Cp\u003E\u003Cb\u003EPatient\u003C/b\u003E\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EName\u003C/b\u003E: 111d3fcaffb244b2b207c07ffa5a14, bf607a7f1f284e8aa3559d52249bc7\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EDOB\u003C/b\u003E: Mar 15, 1936\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EAdministrative Gend
I've tried various suggestions from here including:
final parsed = jsonDecode(body).cast<Map<String, dynamic>>();
Returns
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
I'm quite lost as to what to try next.
You need an array, but your response is a map
You json string is too long, I can not paste full code contains your full json
You can copy paste , replace yourjsonstring and run full code below
Your json string contains control character \n and need to replace before parse
You can get all related class in full code
code snippet
String jsonString = '''yourjsonstring''';
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String resourceType;
String id;
String type;
List<Link> link;
List<Entry> entry;
Payload({
this.resourceType,
this.id,
this.type,
this.link,
this.entry,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
resourceType: json["resourceType"],
id: json["id"],
type: json["type"],
link: List<Link>.from(json["link"].map((x) => Link.fromJson(x))),
entry: List<Entry>.from(json["entry"].map((x) => Entry.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceType,
"id": id,
"type": type,
"link": List<dynamic>.from(link.map((x) => x.toJson())),
"entry": List<dynamic>.from(entry.map((x) => x.toJson())),
};
}
class Entry {
String fullUrl;
Resource resource;
Entry({
this.fullUrl,
this.resource,
});
factory Entry.fromJson(Map<String, dynamic> json) => Entry(
fullUrl: json["fullUrl"],
resource: Resource.fromJson(json["resource"]),
);
Map<String, dynamic> toJson() => {
"fullUrl": fullUrl,
"resource": resource.toJson(),
};
}
class Resource {
ResourceType resourceType;
String id;
Meta meta;
TextClass text;
List<Identifier> identifier;
bool active;
List<Name> name;
List<Telecom> telecom;
Gender gender;
DateTime birthDate;
List<Address> address;
Resource({
this.resourceType,
this.id,
this.meta,
this.text,
this.identifier,
this.active,
this.name,
this.telecom,
this.gender,
this.birthDate,
this.address,
});
factory Resource.fromJson(Map<String, dynamic> json) => Resource(
resourceType: resourceTypeValues.map[json["resourceType"]],
id: json["id"],
meta: Meta.fromJson(json["meta"]),
text: TextClass.fromJson(json["text"]),
identifier: List<Identifier>.from(json["identifier"].map((x) => Identifier.fromJson(x))),
active: json["active"],
name: List<Name>.from(json["name"].map((x) => Name.fromJson(x))),
telecom: List<Telecom>.from(json["telecom"].map((x) => Telecom.fromJson(x))),
gender: genderValues.map[json["gender"]],
birthDate: DateTime.parse(json["birthDate"]),
address: List<Address>.from(json["address"].map((x) => Address.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceTypeValues.reverse[resourceType],
"id": id,
"meta": meta.toJson(),
"text": text.toJson(),
"identifier": List<dynamic>.from(identifier.map((x) => x.toJson())),
"active": active,
"name": List<dynamic>.from(name.map((x) => x.toJson())),
"telecom": List<dynamic>.from(telecom.map((x) => x.toJson())),
"gender": genderValues.reverse[gender],
"birthDate": "${birthDate.year.toString().padLeft(4, '0')}-${birthDate.month.toString().padLeft(2, '0')}-${birthDate.day.toString().padLeft(2, '0')}",
"address": List<dynamic>.from(address.map((x) => x.toJson())),
};
}
class Address {
AddressUse use;
String text;
List<String> line;
String city;
String state;
String postalCode;
String country;
AddressPeriod period;
Address({
this.use,
this.text,
this.line,
this.city,
this.state,
this.postalCode,
this.country,
this.period,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
use: addressUseValues.map[json["use"]],
text: json["text"],
line: List<String>.from(json["line"].map((x) => x)),
city: json["city"],
state: json["state"],
postalCode: json["postalCode"],
country: json["country"],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": addressUseValues.reverse[use],
"text": text,
"line": List<dynamic>.from(line.map((x) => x)),
"city": city,
"state": state,
"postalCode": postalCode,
"country": country,
"period": period == null ? null : period.toJson(),
};
}
class AddressPeriod {
DateTime start;
AddressPeriod({
this.start,
});
factory AddressPeriod.fromJson(Map<String, dynamic> json) => AddressPeriod(
start: DateTime.parse(json["start"]),
);
Map<String, dynamic> toJson() => {
"start": start.toIso8601String(),
};
}
enum AddressUse { HOME, WORK, MOBILE }
final addressUseValues = EnumValues({
"home": AddressUse.HOME,
"mobile": AddressUse.MOBILE,
"work": AddressUse.WORK
});
enum Gender { UNKNOWN, OTHER }
final genderValues = EnumValues({
"other": Gender.OTHER,
"unknown": Gender.UNKNOWN
});
class Identifier {
IdentifierUse use;
Type type;
IdentifierSystem system;
String identifierValue;
Value value;
AddressPeriod period;
Identifier({
this.use,
this.type,
this.system,
this.identifierValue,
this.value,
this.period,
});
factory Identifier.fromJson(Map<String, dynamic> json) => Identifier(
use: identifierUseValues.map[json["use"]],
type: Type.fromJson(json["type"]),
system: identifierSystemValues.map[json["system"]],
identifierValue: json["value"],
value: Value.fromJson(json["_value"]),
period: AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": identifierUseValues.reverse[use],
"type": type.toJson(),
"system": identifierSystemValues.reverse[system],
"value": identifierValue,
"_value": value.toJson(),
"period": period.toJson(),
};
}
enum IdentifierSystem { URN_OID_2168401113883378700, URN_OID_111111, URN_OID_21684011138833421000110000112 }
final identifierSystemValues = EnumValues({
"urn:oid:1.1.1.1.1.1": IdentifierSystem.URN_OID_111111,
"urn:oid:2.16.840.1.113883.3.42.10001.100001.12": IdentifierSystem.URN_OID_21684011138833421000110000112,
"urn:oid:2.16.840.1.113883.3.787.0.0": IdentifierSystem.URN_OID_2168401113883378700
});
class Type {
List<Coding> coding;
TextEnum text;
Type({
this.coding,
this.text,
});
factory Type.fromJson(Map<String, dynamic> json) => Type(
coding: json["coding"] == null ? null : List<Coding>.from(json["coding"].map((x) => Coding.fromJson(x))),
text: textEnumValues.map[json["text"]],
);
Map<String, dynamic> toJson() => {
"coding": coding == null ? null : List<dynamic>.from(coding.map((x) => x.toJson())),
"text": textEnumValues.reverse[text],
};
}
class Coding {
String system;
Code code;
Display display;
bool userSelected;
Coding({
this.system,
this.code,
this.display,
this.userSelected,
});
factory Coding.fromJson(Map<String, dynamic> json) => Coding(
system: json["system"],
code: codeValues.map[json["code"]],
display: displayValues.map[json["display"]],
userSelected: json["userSelected"],
);
Map<String, dynamic> toJson() => {
"system": system,
"code": codeValues.reverse[code],
"display": displayValues.reverse[display],
"userSelected": userSelected,
};
}
enum Code { MR }
final codeValues = EnumValues({
"MR": Code.MR
});
enum Display { MEDICAL_RECORD_NUMBER }
final displayValues = EnumValues({
"Medical record number": Display.MEDICAL_RECORD_NUMBER
});
enum TextEnum { COMMUNITY_MEDICAL_RECORD_NUMBER, MRN, MILITARY_ID }
final textEnumValues = EnumValues({
"Community Medical Record Number": TextEnum.COMMUNITY_MEDICAL_RECORD_NUMBER,
"Military Id": TextEnum.MILITARY_ID,
"MRN": TextEnum.MRN
});
enum IdentifierUse { USUAL }
final identifierUseValues = EnumValues({
"usual": IdentifierUse.USUAL
});
class Value {
List<Extension> extension;
Value({
this.extension,
});
factory Value.fromJson(Map<String, dynamic> json) => Value(
extension: List<Extension>.from(json["extension"].map((x) => Extension.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"extension": List<dynamic>.from(extension.map((x) => x.toJson())),
};
}
class Extension {
String url;
String valueString;
Extension({
this.url,
this.valueString,
});
factory Extension.fromJson(Map<String, dynamic> json) => Extension(
url: json["url"],
valueString: json["valueString"],
);
Map<String, dynamic> toJson() => {
"url": url,
"valueString": valueString,
};
}
class Meta {
String versionId;
DateTime lastUpdated;
Meta({
this.versionId,
this.lastUpdated,
});
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
versionId: json["versionId"],
lastUpdated: DateTime.parse(json["lastUpdated"]),
);
Map<String, dynamic> toJson() => {
"versionId": versionId,
"lastUpdated": lastUpdated.toIso8601String(),
};
}
class Name {
NameUse use;
String text;
List<String> family;
List<String> given;
List<String> prefix;
NamePeriod period;
List<String> suffix;
Name({
this.use,
this.text,
this.family,
this.given,
this.prefix,
this.period,
this.suffix,
});
factory Name.fromJson(Map<String, dynamic> json) => Name(
use: nameUseValues.map[json["use"]],
text: json["text"],
family: List<String>.from(json["family"].map((x) => x)),
given: List<String>.from(json["given"].map((x) => x)),
prefix: json["prefix"] == null ? null : List<String>.from(json["prefix"].map((x) => x)),
period: json["period"] == null ? null : NamePeriod.fromJson(json["period"]),
suffix: json["suffix"] == null ? null : List<String>.from(json["suffix"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"use": nameUseValues.reverse[use],
"text": text,
"family": List<dynamic>.from(family.map((x) => x)),
"given": List<dynamic>.from(given.map((x) => x)),
"prefix": prefix == null ? null : List<dynamic>.from(prefix.map((x) => x)),
"period": period == null ? null : period.toJson(),
"suffix": suffix == null ? null : List<dynamic>.from(suffix.map((x) => x)),
};
}
class NamePeriod {
DateTime start;
DateTime end;
NamePeriod({
this.start,
this.end,
});
factory NamePeriod.fromJson(Map<String, dynamic> json) => NamePeriod(
start: json["start"] == null ? null : DateTime.parse(json["start"]),
end: json["end"] == null ? null : DateTime.parse(json["end"]),
);
Map<String, dynamic> toJson() => {
"start": start == null ? null : start.toIso8601String(),
"end": end == null ? null : end.toIso8601String(),
};
}
enum NameUse { OFFICIAL, OLD }
final nameUseValues = EnumValues({
"official": NameUse.OFFICIAL,
"old": NameUse.OLD
});
enum ResourceType { PATIENT }
final resourceTypeValues = EnumValues({
"Patient": ResourceType.PATIENT
});
class Telecom {
TelecomSystem system;
ValueEnum value;
AddressUse use;
AddressPeriod period;
Telecom({
this.system,
this.value,
this.use,
this.period,
});
factory Telecom.fromJson(Map<String, dynamic> json) => Telecom(
system: telecomSystemValues.map[json["system"]],
value: valueEnumValues.map[json["value"]],
use: addressUseValues.map[json["use"]],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"system": telecomSystemValues.reverse[system],
"value": valueEnumValues.reverse[value],
"use": addressUseValues.reverse[use],
"period": period == null ? null : period.toJson(),
};
}
enum TelecomSystem { PHONE, EMAIL }
final telecomSystemValues = EnumValues({
"email": TelecomSystem.EMAIL,
"phone": TelecomSystem.PHONE
});
enum ValueEnum { THE_3213213213, NAME_FAKEMAIL_COM, THE_8888888888 }
final valueEnumValues = EnumValues({
"name#fakemail.com": ValueEnum.NAME_FAKEMAIL_COM,
"321-321-3213": ValueEnum.THE_3213213213,
"888-888-8888": ValueEnum.THE_8888888888
});
class TextClass {
Status status;
String div;
TextClass({
this.status,
this.div,
});
factory TextClass.fromJson(Map<String, dynamic> json) => TextClass(
status: statusValues.map[json["status"]],
div: json["div"],
);
Map<String, dynamic> toJson() => {
"status": statusValues.reverse[status],
"div": div,
};
}
enum Status { GENERATED }
final statusValues = EnumValues({
"generated": Status.GENERATED
});
class Link {
String relation;
String url;
Link({
this.relation,
this.url,
});
factory Link.fromJson(Map<String, dynamic> json) => Link(
relation: json["relation"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"relation": relation,
"url": url,
};
}
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;
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''yourjsonstring''';
//String jsonString = '''{"newLine": "here is a \n newline \u003E \u0026 \u003C aaa"}''';
void _incrementCounter() {
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
[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(),
);