I am parsing a JSON from Firebase. When I try to decode it with jsonDecode this exception is thrown:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_Map<String, dynamic>' is not a subtype of type 'Map<String, dynamic>'
To reproduce the error:
final Map<String, dynamic>> map = jsonDecode(data);
Data is the following String:
"{
"01/10/2023": {
"enter": "7:0",
"exit": "17:0",
"details": "",
"type": "0005"
},
"01/11/2023": {
"enter": "7:0",
"exit": "17:0",
"details": "",
"type": "0005"
},
"01/12/2023": {
"enter": "7:0",
"exit": "17:0",
"details": "",
"type": "0005"
}
}"
I don't understand why it returns a type that cannot be casted. I don't know the meaning of that underscore.
Try using
final Map<String, dynamic>> map = jsonDecode(data) as Map<String, dynamic>>
Related
I am making an API for the frontlline to return me a list of courses by JSON. However, whatever I tried, I get the below error. Anyone can help?
"status": 400,
"error": "Bad Request",
"trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `com.vtxlab.course.entity.Courses` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `com.vtxlab.course.entity.Courses` from Array value (token `JsonToken.START_ARRAY`)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:391)\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:343)\n\tat org.springframework.web.servlet.mvc.method.annotation.
Here is my API.
#PostMapping(value = "/courses")
public List<Courses> saveAll(#RequestBody List<Courses> courses) {
return courseService.saveAll(courses);
JSON testing:
[
{
"courseName": "DATAANALYSES",
"courseFee": "20000.00",
"startDate": "2022-12-01"
},
{
"courseName": "CSS",
"courseFee": "30000.00",
"startDate": "2022-12-01"
}
]
I want to display the json, but I got the error listed in the title. I have show the line that causing error. Can you help me fix it?
class _MainPage extends State<MainPage> {
List<KomikModel>? listproduk;
Future<List<KomikModel>> _fetchData() async {
final jsondata =
await rootBundle.rootBundle.loadString('assets/datakomik.json');
final list = json.decode(jsondata) as List<dynamic>; // error in this line
return list.map((e) => KomikModel.fromJson(e)).toList();
}
Here is datakomik.json, I use nested json. This is my first time using json, so I don't know how to display the nested json.
{
"data": [
{
"kategori": "New update",
"data": [
{
"judul": "Jujutsu Kaisen",
"image": "images/Jujutsu Kaisen_Volume 1.webp"
},
{
"judul": "Vinland Saga",
"image": "images/Vinland Saga_volume 01.jpg"
},
{
"judul": "Hunter x Hunter",
"image": "images/HxH_Volume 10.jpg"
},
{
"judul": "One Piece",
"image": "images/One Piece_Volume 1.webp"
}
]
},
{
"kategori": "Read",
"data": [
{
"judul": "Kaguya-sama: Love is War",
"image": "images/kaguya-sama_Volume 22.jpg"
}
]
}
]
}
You are receiving a map, and it contains data inside it, You can do
final list = jsonDecode(jsondata)["data"] as List<dynamic>;
You are parsing your JSON as List, but usualy it is Map. Try to handle it similar like this:
final jsondata =
await rootBundle.rootBundle.loadString('assets/datakomik.json');
final objects = json.decode(jsondata) as Map<String, dynamic>;
// And see that data you are recieving.
As you can see in you json file, it contains Map not a list so try this:
final _data = json.decode(jsondata)["data"] as List<dynamic>;
I send a request to server and when the status code is 200 everything is ok i can decode the returned json, but when the status isn't 200 i have a problem
here's the json of status code 200:
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_credential",
"message": "Credential is valid",
"data": {
"token": "a token",
"id": 42626,
"email": "example#gmail.com",
"nicename": "",
"firstName": "",
"lastName": "",
"displayName": ""
}
}
i have adjusted the type of data as a nested structure and it's fine,
the json of else status codes is like this:
{
"success": false,
"statusCode": 403,
"code": "invalid_username",
"message": "Error: The username ** is not registered on this site. If you are unsure of your username, try your email address instead.",
"data": []
}
and here's my problem the returned data value is an empty array and idk how to handle it.
here's my model class:
class loginpagemodel{
late final message;
late final Data data;
loginpagemodel({
this.message,required this.data });
factory loginpagemodel.fromJson(Map<String , dynamic> parsedJson){
return loginpagemodel(
message: parsedJson['message'],
data: Data.fromJson(parsedJson['data']
),
);
}
}
class Data{
late final id;
late final displayName;
Data({this.id,this.displayName});
factory Data.fromJson(Map<String,dynamic> parsedJson){
return Data(
id: parsedJson['id'],
displayName: parsedJson['displayName'],
);
}
}
Thanks for ur answers in advance.
The problem is when the status code isnt 200 the data field is List. A possible solution:
factory loginpagemodel.fromJson(Map<String , dynamic> parsedJson){
return loginpagemodel(
message: parsedJson['message'],
data: Data.fromJson(
parsedJson['data'] == []? // if data is [] (the status code isnt 200)
{} : // empty map
parsedJson['data'] // the data field
),
);
}
You can basically control your data, if it is not empty, you can use.
Just one example;
if(myJson["data"].length == 0 ) {
print("there is no data");
}else{
print("there is data: ${myJson["data"].toString()}");
}
You could make data field nullable: Data? data.
You will need just to check it with "isEmpty" or "isNotEmpty" later.
I've got a problem with parsing JSON to dart object.
This is the class which object I try to get.
class CardDetails {
String cardId;
/*
some fields
/*
List<Mechanics> mechanics;
CardDetails(
{this.cardId,
/*
some fields
/*
this.mechanics});
CardDetails.fromJson(Map<String, dynamic> json) {
cardId = json['cardId'];
/*
some fields
/*
if (json['mechanics'] != null) {
mechanics = new List<Mechanics>();
json['mechanics'].forEach((v) {
mechanics.add(new Mechanics.fromJson(v));
});
}
}
}
class Mechanics {
String name;
Mechanics({this.name});
Mechanics.fromJson(Map<String, dynamic> json) {
name = json['name'];
}
}
And this is a method to get response from API.
Future<CardDetails> getCardDetails(String cardId) async {
Response res = await get(cardDetailsURL + cardId, headers: headers);
if (res.statusCode == 200) {
return CardDetails.fromJson(json.decode(res.body));
} else {
throw Exception('Failed to load details');
}
}
As far as I know getting response works fine.
And this is example JSON
[
{
"cardId": "hexfrog",
"dbfId": "548",
"name": "Frog",
"cardSet": "Basic",
"type": "Minion",
"faction": "Neutral",
"rarity": "Common",
"attack": 0,
"health": 1,
"text": "<b>Taunt</b>",
"race": "Beast",
"playerClass": "Neutral",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/hexfrog.png",
"imgGold": "http://wow.zamimg.com/images/hearthstone/cards/enus/animated/hexfrog_premium.gif",
"locale": "enUS",
"mechanics": [
{
"name": "Taunt"
}
]
}
]
But parsing doesn't work and I'm getting this error:
[ERROR:flutter/shell/common/shell.cc(213)] Dart Error: Unhandled exception:
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
What am I doing wrong?
The JSON you are parsing is a List of maps but in your code you are expecting just a map. If you know the JSON will always just return a single element you can do the following:
CardDetails.fromJson(json.decode(res.body)[0]);
I'm trying to create a sign up model and send it to my API but the "location" Key has another map/jsonobject that contains a "type": "point" and "coordinates": [double, double].
The final json object is supposed to look something like this
{
"name": "Arsh Bansal",
"email": "ab#yahoo.com",
"password": "123456789",
"birthday": "06-21-2000",
"gender": "Male",
"location": {
"type": "Point",
"coordinates": [13.0987, 88.403]
},
"phone_number": "123456789"
}
The error I get is :
Unhandled Exception: type '_InternalLinkedHashMap<String, List>' is not a subtype of type 'String' in type cast
Use this
class Location {
String type;
List<double> coordinates;
Location({this.type, this.coordinates});
Location.fromJson(Map<String, dynamic> json) {
type = json['type'];
coordinates = json['coordinates'].cast<double>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['coordinates'] = this.coordinates;
return data;
}
}