fetching json data and creating a list - json

I'm currently studying flutter and I'm creating an app on my own...
So the problem at the moment is that I need to fetch json data and to put it in the list, in this case listOfCards (custom made object Card contains initialSearch as String and results as List. I've been following this example https://flutter.dev/docs/cookbook/networking/background-parsing#convert-the-response-into-a-list-of-photos but there they are directly parsing data into app and I really didn't know how to use it in my case.
I need to fill this listOfCards List to use it later in the app.
So here's the code:
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
List<Card> listOfCards = [];
Future<List<Card>> fetchCards(http.Client client) async {
final response = await client.get(
Uri.parse('605a2f18b11aba001745dbdd.mockapi.io/api/v1/cards'),
);
return parseCards(response.body);
}
List<Card> parseCards(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Card>((json) => Card.fromJson(json)).toList();
}
class Card {
String initialSearch;
List<String> mostPopularSearches;
Card({
this.initialSearch,
this.mostPopularSearches,
});
factory Card.fromJson(Map<String, dynamic> json) {
return Card(
initialSearch: json['search'] as String,
mostPopularSearches: json['results'] as List,
);
}
}

Custome class
class Card {
String initialSearch;
List<String> mostPopularSearches;
Card({this.initialSearch, this.mostPopularSearches});
Card.fromJson(Map<String, dynamic> json) {
initialSearch = json['initialSearch'];
mostPopularSearches = json['mostPopularSearches'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['initialSearch'] = this.initialSearch;
data['mostPopularSearches'] = this.mostPopularSearches;
return data;
}
}
Generated using Json to dart
To store the responses as Card object
Card _card = Card.fromJson(responsebody);
Your response JSON
{
"initialSearch": "Google",
"mostPopularSearches": [
"Google",
"Facebook",
"Stacjoverflow",
"Reddit"
]
}

Related

Flutter : How to parse JSON Array of objects

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));
});

FLUTTER/DARTTrying to convert a List<T> to JsonString to save in sharedPreferences. <T> has a Contact object and bool value

Trying to save a list in shared sharedpreferences by converting to JsonString. But repeatedly getting the encodable object failed : Instance of 'CustonContact'. Help out
class CustomContact extends Contact{
Contact contact;
bool isChecked;
CustomContact({
this.contact,
this.isChecked = false,
});
Map toJson() {
return {
'contact': contact,
'isChecked': isChecked,
};
}
CustomContact.fromJson(Map<String, dynamic> json)
: contact = json['contact'],
isChecked = json['isChecked'];
}
****Trying to call it in here to save in sharedpreference****
_saveTrustedContactsNames() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
List<CustomContact> _contactsSelectedNames = [];
for (var _customContact in contactsSelected) { **contactsSelected is already populated**
setState(() {
_contactsSelectedNames.add(_customContact);
});
}
**trying to convert to JsonString**
String _trustedContactsJson = jsonEncode(_contactsSelectedNames);
print(_trustedContactsJson);
preferences.setString('_contactstrusted', _trustedContactsJson);
}
That's cause sharedPreferences can't automatically convert Contact to json. You'll need to create a toJson method in Contact and pass that method in to your CustomContact's toJson method and vice versa for the fromJson.
Map toJson() {
return {
'contact': contact.toJson(),
'isChecked': isChecked,
};
}
CustomContact.fromJson(Map<String, dynamic> json)
: contact = Contact.fromJson(json['contact']),
isChecked = json['isChecked'];

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,
};
}

Flutter parsing JSON with array

I have troubles with parsing a JSON file with array.
It looks like something like this:
{
"status": "200",
"addresses": [
{
"address": "Address 1"
},
{
"address": "Address 2"
}
]
}
And I tried to parse it with:
var response = jsonDecode(res.body);
print(response['addresses']['address'][0]);
print(response['addresses']['address'][1]);
But it is not working. Is there any common pattern how this should be?
That's because you're not accessing it the right way. You have a Map<String,dynamic> that has a List<Map<String,String>> for the key addresses.
If you want to access the first two elements of that list, you can do it by doing:
var response = jsonDecode(res.body);
print(response['addresses'][0]['address']);
print(response['addresses'][1]['address']);
The easiest way I have found for dealing with this is to have this website write the JSON parser for me. Simply copy / paste you JSON into provide field and choose Dart as the language:
https://app.Quicktype.io
Your best mapping the data into a class there is a useful website (created by Javier Lecuona) that generates the class for you. https://javiercbk.github.io/json_to_dart/
Here is an example:
var parsedJson = jsonDecode(json);
var addressList = ClientAddresses.fromJson(parsedJson);
print(addressList.addresses[0].address);
print(addressList.addresses[1].address);
class ClientAddresses {
String status;
List<Addresses> addresses;
ClientAddresses({this.status, this.addresses});
ClientAddresses.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['addresses'] != null) {
addresses = new List<Addresses>();
json['addresses'].forEach((v) {
addresses.add(new Addresses.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.addresses != null) {
data['addresses'] = this.addresses.map((v) => v.toJson()).toList();
}
return data;
}
}
class Addresses {
String address;
Addresses({this.address});
Addresses.fromJson(Map<String, dynamic> json) {
address = json['address'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['address'] = this.address;
return data;
}
}