Flutter : How to parse JSON Array of objects - json

Can anyone tell me how to parse arrays of object in flutter. When I am parsing the json I am getting error as List is not a subtype of type Map<String, dynamic>.
Below is my json file which needs to be parsed. Please help me to fix this issue.
[
{
"empPayslipsId": "2021012000440",
"month": "Jan",
"description": "Payslip for JAN 2021 (Month End)",
"paymentPeriod": "1/1/2021 12:00:00 AM - 1/31/2021 12:00:00 AM",
"lastAccessBy": "0002\r\n118.200.199.70",
"lastAccessDate": "20210202",
"lastAccessTime": "105706",
"successAccess": "2",
"failAccess": "2"
}
]
Future<void> loadQueryPeriod(int year, var month) async {
String baseURL = '${domainURL}api/PaySlip?year=$year&month=$month';
try {
final response = await http.get(baseURL, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization':
'Bearer ${Provider.of<UserVM>(navigatorKey.currentContext, listen: false).accessToken}',
});
print('UIC PDF response : ${response.body}');
print(
'UIC Token response : ${Provider.of<UserVM>(navigatorKey.currentContext, listen: false).accessToken}');
if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
print('result type: ${data.runtimeType}');
}
} catch (e) {
print(e);
throw Exception('Download PDF Fail! ${e.toString()}');
}
}
}

Change it to this:
final Map<String, dynamic> data = json.decode(response.body)[0];
This is because your map is inside a list. Look at the square brackets [ ] enclosing your map. The map that you need, is at index[0] of this list.

use this podo class :
// Generated by https://quicktype.io
// To parse this JSON data, do
//
// final sample = sampleFromJson(jsonString);
import 'dart:convert';
List<Sample> sampleFromJson(String str) {
final jsonData = json.decode(str);
return new List<Sample>.from(jsonData.map((x) => Sample.fromJson(x)));
}
String sampleToJson(List<Sample> data) {
final dyn = new List<dynamic>.from(data.map((x) => x.toJson()));
return json.encode(dyn);
}
class Sample {
String empPayslipsId;
String month;
String description;
String paymentPeriod;
String lastAccessBy;
String lastAccessDate;
String lastAccessTime;
String successAccess;
String failAccess;
Sample({
this.empPayslipsId,
this.month,
this.description,
this.paymentPeriod,
this.lastAccessBy,
this.lastAccessDate,
this.lastAccessTime,
this.successAccess,
this.failAccess,
});
factory Sample.fromJson(Map<String, dynamic> json) => new Sample(
empPayslipsId: json["empPayslipsId"],
month: json["month"],
description: json["description"],
paymentPeriod: json["paymentPeriod"],
lastAccessBy: json["lastAccessBy"],
lastAccessDate: json["lastAccessDate"],
lastAccessTime: json["lastAccessTime"],
successAccess: json["successAccess"],
failAccess: json["failAccess"],
);
Map<String, dynamic> toJson() => {
"empPayslipsId": empPayslipsId,
"month": month,
"description": description,
"paymentPeriod": paymentPeriod,
"lastAccessBy": lastAccessBy,
"lastAccessDate": lastAccessDate,
"lastAccessTime": lastAccessTime,
"successAccess": successAccess,
"failAccess": failAccess,
};
}
Now inorder to parse json call,
Sample sample = sampleFromJson(jsonString);
via this you will get the access to sample PODO class and you can access any object you want.

The initial data you received by calling a get request isn't stored in a map, but rather in a list.
You should do something like this to receive your initial data.
if (response.statusCode == 200) {
final List<dynamic> data = json.decode(response.body);
}
From there, they're numerous ways to get the data from your data variable. You can use lists here if you want, for example to get the value of month in the JSON.
final String month = data[0]['month'];
If you'd prefer to use Maps, the syntax it'll look like this
final Map<String, dynamic> endpointData = data[0];
final String responseKey = 'month';
final var result = endpointData[responseKey];

if you have data model you can do it like this
fromJsonList(List<dynamic> jsonList) {
List<YourModel> yourModelList = [];
jsonList.forEach((jsonModel) {
menuModelsOfferList.add(YourModel.fromJson(jsonModel));
});

Related

How to convert data from json to List<Object> in Flutter

I need to obtain a list of Articles(a custom object) from a realtime database in Firebase. I first decode my data from a json data type. Then I try to convert it into a list using this line of code:
List<Article> articles = List<Article>.from(articleResponse)
.map((Map model) => Article.fromJson(model))
.toList();
However, this gives a syntax error of "The argument type 'Article Function(Map<dynamic,dynamic>)' can't be assigned to the parameter type 'dynamic Function(Article)'." I have included the code I use to fetch an Article(the custom object) as well as the factory method for the class.
//Method to get articles
Future<List<Article>> fetchArticles() async {
final response = await http.get(
"https://some-server.firebaseio.com/some-url.json");
final articleResponse = json.decode(response.body);
List<Article> articles = List<Article>.from(articleResponse)
.map((Map model) => Article.fromJson(model))
.toList(); // Now we're looping over the response entries (maps of article info) to create Article instances
return articles;
}
\\Factory Method
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
title: json['title'],
author: json['author'],
date: json['date'],
imageUrl: json['imageUrl'],
modalities: json['modalities'],
);
}
I make an example with something like a json response.
void main() {
//this is an example like a json response
List<Map<String, dynamic>> articleResponse = [
{
"id":"1",
"name":"test1"
},
{
"id":"2",
"name":"test2"
}
];
List<Article> articles = List<Article>.from(articleResponse.map((Map art)=>Article.fromJson(art)))
.toList();
print('${articles.length} articles in the list!! use to render de ui list');
}
class Article{
String id;
String name;
Article({this.id,this.name});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
name: json['name'],
);
}
}
basically you need to change your method to get articles with this.
//Method to get articles
Future<List<Article>> fetchArticles() async {
final response = await http.get(
"https://some-server.firebaseio.com/some-url.json");
final articleResponse = json.decode(response.body);
List<Article> articles = List<Article>.from(articleResponse.map((Map art)=>Article.fromJson(art)))
.toList(); // Now we're looping over the response entries (maps of article info) to create Article instances
return articles;
}
you can use JsonToDart
this is create a class for parse your complex json data
paste json and get class of model
you can overrride toString in your model like:
#override
String toString() {
return '{
id: $id,
title: $title,
author: $author,
date: $date,
imageUrl: $imageUrl,
modalities: $modalities
}';
}
and override toMap :
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'title': title,
'author': author,
'date': date,
'imageUrl': imageUrl,
'modalities': modalities,
};
}
and you can use serialization that. this can help you

_CastError (type 'Client' is not a subtype of type 'List<dynamic>' in type cast)

My API returns the following response:
[{id: 1, nome: foo}, {id: 2, nome: bar}]
And I created a model Client to represent each one:
class Client {
final int id;
final String name;
Client({
this.id,
this.name,
});
factory Client.fromJson(Map<String, dynamic> json) {
return Client(
id: json['id'],
name: json['nome'],
);
}
Map<String, dynamic> toJson() => {
'id': id,
'nome': name,
};
}
Then, in my repository, the method fetching the data above is as follows:
Future<List<Client>> getClients() async {
try {
final _response = await _dio.get(
'/clientes',
options: Options(
headers: {'Authorization': 'Bearer $TOKEN'},
),
);
return Client.fromJson(_response.data[0]) as List; // Error pointed to this line
} on DioError catch (_e) {
throw _e;
}
}
Being stored here
#observable
List<Client> clients;
I am not sure what to do. What am I doing wrong?
dio will decode the response and you'll get a List<dynamic>. Use List.map to convert it to a list of clients, by passing a function that will turn a Map<String, dynamic> into a Client. (You already have one - the named constructor.)
For example:
var dioResponse = json.decode('[{"id": 1, "nome": "foo"}, {"id": 2, "nome": "bar"}]');
List<dynamic> decoded = dioResponse;
var clients = decoded.map<Client>((e) => Client.fromJson(e)).toList();
You're trying to cast a Client as a List<dynamic> which isn't a valid cast since Client doesn't implement List. If you want to return a List containing a single Client, you'll want to change the line with the error to:
return [Client.fromJson(_response.data[0])];

How to pass a list of json to body of http request (post) in Flutter?

I have objects that will filled by a user in a form. I parse these objects to json and add that json in a list to pass in body of request. But i cant do this.
incrementListPaymentSlipes(PaymentSlipes objPayment) async {
objPayment.name = "Douglas";
objPayment.personalId = "00000000000";
Map<String, dynamic> json = objPayment.toJson();
listPaymentSlipes.add(jsonEncode(json));
}
var response = await http.post(url, body: {
"payment_slips": listPaymentSlipes,
}
example of correct body:
"payment_slips": [
{
"personal_id": "01888728680",
"name": "Fulano da Silva"
}
]
{"error":"'{{personal_id: 00000000000, name: Douglas}}' é invalido como 'payment_slips'","code":"payment_slips_invalid"}```
You can do it in a very simple way. Create payment.dart file and copy paste the below code classes.
class PaymentList {
PaymentList(this.payments);
List<Payment> payments;
Map<String, dynamic> toJson() => <String, dynamic>{
'payment_slips': payments,
};
}
class Payment {
Payment({this.name, this.personalId});
String name;
String personalId;
Map<String, dynamic> toJson() => <String, dynamic>{
'personal_id': personalId,
'name': name,
};
}
Now you can covert it to the required json format using below code. For example I am creating a dummy list:
final PaymentList paymentList =
PaymentList(List<Payment>.generate(2, (int index) {
return Payment(name: 'Person $index', personalId: '$index');
}));
final String requestBody = json.encoder.convert(paymentList);
The requestBody variable will have the json string as follows:
{"payment_slips": [
{
"personal_id": "0",
"name": "Person 0"
},
{
"personal_id": "1",
"name": "Person 1"
}
]}
Now you can call the api:
var response = await http.post(url, body: requestBody}
Note: Please import the below package, which will be required to access json:
import 'dart:convert';
So it looks like you are not getting the JSON you expect. I have put together some code to show you how to get the body you want.
Link to run in DartPad https://dartpad.dartlang.org/3fde03078e56efe13d31482dea8e5eef
class PaymentSlipes {
String name;
String personaId;
ObjPayment({this.name, this.personaId});
//You create this to convert your object to JSON
Map<String, dynamic> toJson() => {'name': name, 'personaId': personaId};
}
// This method is needed to convert the list of ObjPayment into an Json Array
List encondeToJson(List<PaymentSlipes> list) {
List jsonList = List();
list.map((item) => jsonList.add(item.toJson())).toList();
return jsonList;
}
// This is an example and this code will run in DartPad link above
void main() {
PaymentSlipes objPayment = PaymentSlipes(name: "Douglas", personaId: "123425465");
PaymentSlipes objPayment2 = PaymentSlipes(name: "Dave", personaId: "123425465;
PaymentSlipes objPayment3 = PaymentSlipes(name: "Mike", personaId: "123425465");
var list = [objPayment, objPayment2, objPayment3];
// This is the mapping of the list under the key payment_slips as per your example and the body i would pass to the POST
var finalJson = {"payment_slips": encondeToJson(list)};
print(finalJson);
}

how to encode and send to server json list by dio

i have class that generate json list this is my class
class Tool{
String Name;
bool selection;
String englishName;
Map<String, dynamic> toJson() {
return {
'Name': persianName,
'selection': selection,
'englishName': englishName
};
}
}
List<Tool> tools=new List();
setTool(tool){
tools.add(tool);
}
toolsLength(){
return tools.length;
}
updatetool(index,goal){
tools[index]=goal;
}
getTool(index){
return tools[index];
}
getAllTools(){
return tools;
}
and this is dio library that send my list to server every thing is ok but my array is into Double quotation in other word my list is string how to pick up double quotation around of json array . if assume my json array hase
"tools": [{"name":"jack","selection" : false " ,"englishName":"jock"}]
result is :
"tools": "[{"name":"jack","selection" : false " ,"englishName":"jock"}]"
how fix it this is my class for send
FormData formData = new FormData.from({
"tools":jsonEncode(getAllTools().map((e) => e.toJson()).toList()) ,
});
response = await
dio.post("${strings.baseurl}/analyze/$username/$teacher", data:
formData);
print("----------> response is :"+response.toString());
Edit
You can paste the following code to DarPad https://dartpad.dartlang.org/
The following demo shows transform your Json String to Tool List and Convert your Tool List to JSON string again and use map.toJson
var yourresult = toolList.map((e) => e.toJson()).toList();
you can see result in picture
use FormData.from need to know what your api's correct JSON String.
Please test your web api with Postman, if you success, you will know correct format string.
In your code
FormData formData = new FormData.from({
"tools":jsonEncode(getAllTools().map((e) => e.toJson()).toList()) ,
});
if you are trying to to do
FormData formData = new FormData.from({
"tools":'[{"name":"jack","selection" : false ,"englishName":"jock"}, {"name":"jack2","selection" : false ,"englishName":"jock2"}]' ,
});
so you can get your json string first and put it in FormData
var toolsJson = toolsToJson(toolList);
FormData formData = new FormData.from({
"tools":toolsJson ,
});
full demo code, you can paste to DartPad to see string and list conversion
import 'dart:async';
import 'dart:io';
import 'dart:core';
import 'dart:convert';
class Tools {
String name;
bool selection;
String englishName;
Tools({
this.name,
this.selection,
this.englishName,
});
factory Tools.fromJson(Map<String, dynamic> json) => new Tools(
name: json["name"],
selection: json["selection"],
englishName: json["englishName"],
);
Map<String, dynamic> toJson() => {
"name": name,
"selection": selection,
"englishName": englishName,
};
}
main() {
List<Tools> toolsFromJson(String str) => new List<Tools>.from(json.decode(str).map((x) => Tools.fromJson(x)));
String toolsToJson(List<Tools> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));
var toolsStr = '[{"name":"jack","selection" : false ,"englishName":"jock"}, {"name":"jack2","selection" : false ,"englishName":"jock2"}]';
var toolList = toolsFromJson(toolsStr);
var toolsJson = toolsToJson(toolList);
print("toolsJson ${toolsJson} \n");
var toolsmap = toolList[0].toJson();
print("toolsmap ${toolsmap.toString()}\n");
var yourresult = toolList.map((e) => e.toJson()).toList();
print(yourresult.toString());
}
you can paste your JSON string to https://app.quicktype.io/, you will get correct Dart class
correct JSON string of your sample. in false keyword followed by a " cause JSON string parsing error.
[
{"name":"jack",
"selection" : false ,
"englishName":"jock"
}
]
code to parse JSON string and encode to List, use toJson will convert to JSON string you need to send with dio form
// To parse this JSON data, do
//
// final tools = toolsFromJson(jsonString);
import 'dart:convert';
List<Tools> toolsFromJson(String str) => new List<Tools>.from(json.decode(str).map((x) => Tools.fromJson(x)));
String toolsToJson(List<Tools> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));
class Tools {
String name;
bool selection;
String englishName;
Tools({
this.name,
this.selection,
this.englishName,
});
factory Tools.fromJson(Map<String, dynamic> json) => new Tools(
name: json["name"],
selection: json["selection"],
englishName: json["englishName"],
);
Map<String, dynamic> toJson() => {
"name": name,
"selection": selection,
"englishName": englishName,
};
}

fromMap is assigning null values from json reponse

I am trying to assign JSON response dart Entity using fromJson but the return object is having all null values.
The json looks like below:
{
"doc":{
"id":"6496772",
"name":"Test Document",
}
"custom_keys":[
{
"key": "X1",
"name":"X1"
},
{
"key": "X2",
"name":"X2"
},
]
}
I have created Test Entity as below
class Test{
final String id;
final String name;
const Feature({
this.id,
this.name,
});
Feature.fromMap(Map<String, dynamic> map) :
id= map['id'],
name= map['name'];
}
API method:
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(UTF8.decoder).join();
print(json.toString());
var data = JSON.decode(json);
return new Test.fromMap(data['doc']);
// getting null object from above return statement
There is error message. what could be the issue ?
the null object probably comes from id= map['id'], while your json only returns "key" and "name".
you have to map each json element to a property. changing the constructor to
Feature.fromMap(Map<String, dynamic> map) :
id= map['key'],
name= map['name'];
will probably do the trick.