I have a kind of POJO class in Dart and I want to map the variables using an API call.
Here is my POJO class in Code.1,
class Elements {
String onApi;
String tlApi;
String pl1Api;
String pl2Api;
String dl1Api;
String dl2Api;
String fnApi;
String lnApi;
String cnApi;
String eidApi;
Elements(
{this.onApi,
this.tlApi,
this.pl1Api,
this.pl2Api,
this.dl1Api,
this.dl2Api,
this.fnApi,
this.lnApi,
this.cnApi,
this.eidApi});
Elements.fromJson(Map<String, dynamic> json) {
onApi = json['on_api'];
tlApi = json['tl_api'];
pl1Api = json['pl1_api'];
pl2Api = json['pl2_api'];
dl1Api = json['dl1_api'];
dl2Api = json['dl2_api'];
fnApi = json['fn_api'];
lnApi = json['ln_api'];
cnApi = json['cn_api'];
eidApi = json['eid_api'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['on_api'] = this.onApi;
data['tl_api'] = this.tlApi;
data['pl1_api'] = this.pl1Api;
data['pl2_api'] = this.pl2Api;
data['dl1_api'] = this.dl1Api;
data['dl2_api'] = this.dl2Api;
data['fn_api'] = this.fnApi;
data['ln_api'] = this.lnApi;
data['cn_api'] = this.cnApi;
data['eid_api'] = this.eidApi;
return data;
}
}
Code.1
Here is the JSON code which I want to map via an API call in Code.2,
{
"on_api": "1",
"tl_api": "10",
"pl1_api": "XYZ Chocolates Lounge",
"pl2_api": "ABC Nagar",
"dl1_api": "EFGH Software Pvt. Ltd.",
"dl2_api": "Random Road, Bengaluru - 5600XX",
"fn_api": "Snehanshu",
"ln_api": "Bhattacharya",
"cn_api": "01234",
"eid_api": "snehanshu#abc.com"
}
Code.2
Here is my API calling class Code.3,
import 'dart:convert';
import 'package:http/http.dart';
import 'package:smoorapplication/src/constants/constants.dart';
import 'package:smoorapplication/src/model/elements.dart';
Future<dynamic> apiGetOrder() async{
var response = await get(Uri.parse(API_LINK));
var jsonData = jsonDecode(response.body);
List<Elements> elements = [];
for(var u in jsonData){
Elements element =
Elements.fromJson(u);
elements.add(element);
}
print(elements.length);
return elements;
}
Code.3
So, I need some help in writing the code for the API call, so that it can map the data successfully.
Thank you
your model class
import 'dart:convert';
Element elementFromJson(String str) => Element.fromJson(json.decode(str));
String elementToJson(Element data) => json.encode(data.toJson());
class Element {
Element({
this.onApi,
this.tlApi,
this.pl1Api,
this.pl2Api,
this.dl1Api,
this.dl2Api,
this.fnApi,
this.lnApi,
this.cnApi,
this.eidApi,
});
String onApi;
String tlApi;
String pl1Api;
String pl2Api;
String dl1Api;
String dl2Api;
String fnApi;
String lnApi;
String cnApi;
String eidApi;
factory Element.fromJson(Map<String, dynamic> json) => Element(
onApi: json["on_api"],
tlApi: json["tl_api"],
pl1Api: json["pl1_api"],
pl2Api: json["pl2_api"],
dl1Api: json["dl1_api"],
dl2Api: json["dl2_api"],
fnApi: json["fn_api"],
lnApi: json["ln_api"],
cnApi: json["cn_api"],
eidApi: json["eid_api"],
);
Map<String, dynamic> toJson() => {
"on_api": onApi,
"tl_api": tlApi,
"pl1_api": pl1Api,
"pl2_api": pl2Api,
"dl1_api": dl1Api,
"dl2_api": dl2Api,
"fn_api": fnApi,
"ln_api": lnApi,
"cn_api": cnApi,
"eid_api": eidApi,
};
}
and here's your getAPiOrder method
Future<dynamic> apiGetOrder() async{
var response = await get(Uri.parse(API_LINK));
///if this line doesn't work
Element element = Element.fromJson(respnse.body);
///try this line
Element element = Element.fromJson(Map.from(respnse.body));
return elements;
}
Related
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"
]
}
I want to send data like
[
{
"QuizTitle": "QuizList1Title",
"QuizDesc": "QuizList1Description",
"Question": "List1Question1",
"Choice1": "List1choice1",
"Choice2": "List1choice2",
"Choice3": "List1choice3",
"Choice4": "List1choice4",
"CorrectAns": "ListcorrectAns1"
},
{
"QuizTitle": "QuizList2Title",
"QuizDesc": "QuizList2Description",
"Question": "List2Question1",
"Choice1": "List2choice1",
"Choice2": "List2choice2",
"Choice3": "List2choice3",
"Choice4": "List2choice4",
"CorrectAns": "ListcorrectAns2"
},
]
to my webapi from flutter any leads how I can achieve this?
Use the following POJO class as request. and set your parameters.
class Autogenerated {
String quizTitle;
String quizDesc;
String question;
String choice1;
String choice2;
String choice3;
String choice4;
String correctAns;
Autogenerated(
{this.quizTitle,
this.quizDesc,
this.question,
this.choice1,
this.choice2,
this.choice3,
this.choice4,
this.correctAns});
Autogenerated.fromJson(Map<String, dynamic> json) {
quizTitle = json['QuizTitle'];
quizDesc = json['QuizDesc'];
question = json['Question'];
choice1 = json['Choice1'];
choice2 = json['Choice2'];
choice3 = json['Choice3'];
choice4 = json['Choice4'];
correctAns = json['CorrectAns'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['QuizTitle'] = this.quizTitle;
data['QuizDesc'] = this.quizDesc;
data['Question'] = this.question;
data['Choice1'] = this.choice1;
data['Choice2'] = this.choice2;
data['Choice3'] = this.choice3;
data['Choice4'] = this.choice4;
data['CorrectAns'] = this.correctAns;
return data;
}
}
After that use json.encode() to encode object into json and using dio send the api request.
I am trying to call Name and Fees from my json code
it is nested array from main array of my json the main array i can deal with it but the sub array i can't
"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
],
And I can't do that because of the error here when iam tring to call 'Name' and 'Fees'
type 'List<ExtraServices>' is not a subtype of type 'String'
and this is my class for mapping tour guide data to use it in list view
class TourGuide{
String id;
String name;
String email;
String password;
List<ExtraServices> extraService;
TourGuide({
this.id,
this.name,
this.email,
this.password,
this.extraService,
});
TourGuide.fromJson(Map<String, dynamic> json){
List<dynamic> extra = json['guideExtraServices'];
List<ExtraServices> extraList = extra.map((i) => ExtraServices.fromJson(i)).toList();
id = json['id'].toString();
name = json['displayName'];
email = json['email'];
password = json['password'];
extraService=extraList;
}
}
and this is a Extra Services class which tour guide class depend on to get the sub array
class ExtraServices{
String name;
double fees;
ExtraServices({
this.name,
this.fees
});
ExtraServices.fromJson(Map<String, dynamic> json){
name = json['Name'];
fees = json['Fees'].toDouble();
}
}
my provider method for decode json using for api
Future<dynamic> tourGuideList() async {
_isLoading = true;
notifyListeners();
print('Starting request');
http.Response response = await http.get(Environment.tourGuide,
headers: Environment.requestHeader);
print('Completed request');
print('respond data : ${response.body}');
Map<String, dynamic> res = json.decode(response.body);
var results;
if (res['code'] == 200) {
print('start load tourguide');
_tourGuide = [];
res['message'].forEach((v) {
_tourGuide.add(new TourGuide.fromJson(v));
});
results = true;
} else {
results =
FailedRequest(code: 400, message: res['error'], status: false);
}
_isLoading = false;
notifyListeners();
return results;
}
and I don't know why I have an error and I can't fix it
I think your json should be like this in total:
{"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
]}
Try
// To parse this JSON data, do
//
// final tourGuide = tourGuideFromJson(jsonString);
import 'dart:convert';
TourGuide tourGuideFromJson(String str) => TourGuide.fromJson(json.decode(str));
String tourGuideToJson(TourGuide data) => json.encode(data.toJson());
class TourGuide {
List<GuideExtraService> guideExtraServices;
TourGuide({
this.guideExtraServices,
});
factory TourGuide.fromJson(Map<String, dynamic> json) => TourGuide(
guideExtraServices: List<GuideExtraService>.from(json["guideExtraServices"].map((x) => GuideExtraService.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"guideExtraServices": List<dynamic>.from(guideExtraServices.map((x) => x.toJson())),
};
}
class GuideExtraService {
String name;
int fees;
GuideExtraService({
this.name,
this.fees,
});
factory GuideExtraService.fromJson(Map<String, dynamic> json) => GuideExtraService(
name: json["Name"],
fees: json["Fees"],
);
Map<String, dynamic> toJson() => {
"Name": name,
"Fees": fees,
};
}
Please try the below code :-
First Create Model :-
class GuideResponseModel {
List<GuideExtraServicesModel> guideExtraServiceList;
GuideResponseModel({
this.guideExtraServiceList
});
factory GuideResponseModel.fromJson(Map<String, dynamic> parsedJson) {
try {
List<GuideExtraServicesModel> guideExtraServiceModelList = new List();
if (parsedJson.containsKey('guideExtraServices')) {
var countryList = parsedJson['guideExtraServices'] as List;
guideExtraServiceModelList =
countryList.map((i) => GuideExtraServicesModel.fromJson(i)).toList();
}
return GuideResponseModel(
guideExtraServiceList: guideExtraServiceModelList
);
} catch (e) {
return null;
}
}
}
class GuideExtraServicesModel {
String name;
int fees;
GuideExtraServicesModel({this.name,this.fees});
factory GuideExtraServicesModel.fromJson(Map<String, dynamic> json) {
return GuideExtraServicesModel(name: json['Name'],fees: json['Fees']);
}
}
Second User the Model:-
String jsonData = '{"guideExtraServices": [{"Name": "Limousine","Fees": 100},{"Name": "Bus","Fees": 10000},{"Name": "Mini-Bus","Fees": 5000}]}';
final dynamic jsonResponse = json.decode(jsonData);
final GuideResponseModel responseModel = GuideResponseModel.fromJson(jsonResponse);
print('======${responseModel.guideExtraServiceList[0].name}----${responseModel.guideExtraServiceList[0].fees}');
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,
};
}
I am trying to work with firebase database from flutter. I have made a model class which I am converting to json and from json via plugin json_serializable. Where model class works perfectly fine with hard coded json data but when I am trying to save the encoded data to firebase database it's getting saved as a string instead of key value pair in firebase database.Below is my code to convert it and save it
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
//print(json.encode(egluCard));
// var jsonString = '{"isInternal":true,"isPublished":true,"title":"HI","body":"World","caption":"Awesome","cardType":"TYPE_1","images":["images"],"expiry":123,"showAt":125,"bgColor":"#FFFFFF","platformType":"IOS","actions":[{"label":"This is label","url":"mranuran.com"}]}';
// Map<String,dynamic> cardMap = json.decode(jsonString);
// EgluCard egluCard = EgluCard.fromJson(cardMap);
// print(egluCard.actions[0].label);
var jsonString = json.encode(egluCard);
var trimmedString = jsonString.substring(0,jsonString.length);
print(trimmedString);
cardsDBRef.push().set(jsonString)
.then((_){
print('saved!!');
});
when I am printing the json.encode(eGluCard) then it's printing a valid json but when it's getting saved into firebase I am getting the following from firebase. It was supposed to save as key value pair but it was saved as a whole string.
"{\"isInternal\":true,\"isPublished\":true,\"title\":\"HI\",\"body\":\"World\",\"caption\":\"Awesome\",\"cardType\":\"TYPE_1\",\"images\":[\"images\"],\"expiry\":123,\"showAt\":125,\"bgColor\":\"#FFFFFF\",\"platformType\":\"IOS\",\"actions\":[{\"label\":\"This is label\",\"url\":\"mranuran.com\"}]}"
what can be wrong in this approach? below are my model classed and their generated serializer respectively
EgluCard.dart
import 'card_type.dart';
import 'platform_type.dart';
import 'action.dart';
import 'package:json_annotation/json_annotation.dart';
part 'eglu_card.g.dart';
#JsonSerializable()
class EgluCard {
bool isInternal;
bool isPublished;
String title;
String body;
String caption;
CardType cardType;
List<String> images;
int expiry;
int showAt;
String bgColor;
PlatformType platformType;
List<Action> actions;
EgluCard(this.isInternal,this.isPublished,this.title,this.body,this.caption,this.cardType,this.images,
this.expiry,this.showAt,this.bgColor,this.platformType,this.actions);
factory EgluCard.fromJson(Map<String, dynamic> json) => _$EgluCardFromJson(json);
Map<String, dynamic> toJson() => _$EgluCardToJson(this);
}
EgluCard Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'eglu_card.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
EgluCard _$EgluCardFromJson(Map<String, dynamic> json) {
return EgluCard(
json['isInternal'] as bool,
json['isPublished'] as bool,
json['title'] as String,
json['body'] as String,
json['caption'] as String,
_$enumDecodeNullable(_$CardTypeEnumMap, json['cardType']),
(json['images'] as List)?.map((e) => e as String)?.toList(),
json['expiry'] as int,
json['showAt'] as int,
json['bgColor'] as String,
_$enumDecodeNullable(_$PlatformTypeEnumMap, json['platformType']),
(json['actions'] as List)
?.map((e) =>
e == null ? null : Action.fromJson(e as Map<String, dynamic>))
?.toList());
}
Map<String, dynamic> _$EgluCardToJson(EgluCard instance) => <String, dynamic>{
'isInternal': instance.isInternal,
'isPublished': instance.isPublished,
'title': instance.title,
'body': instance.body,
'caption': instance.caption,
'cardType': _$CardTypeEnumMap[instance.cardType],
'images': instance.images,
'expiry': instance.expiry,
'showAt': instance.showAt,
'bgColor': instance.bgColor,
'platformType': _$PlatformTypeEnumMap[instance.platformType],
'actions': instance.actions
};
T _$enumDecode<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
throw ArgumentError('A value must be provided. Supported values: '
'${enumValues.values.join(', ')}');
}
return enumValues.entries
.singleWhere((e) => e.value == source,
orElse: () => throw ArgumentError(
'`$source` is not one of the supported values: '
'${enumValues.values.join(', ')}'))
.key;
}
T _$enumDecodeNullable<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
return null;
}
return _$enumDecode<T>(enumValues, source);
}
const _$CardTypeEnumMap = <CardType, dynamic>{CardType.TYPE_1: 'TYPE_1'};
const _$PlatformTypeEnumMap = <PlatformType, dynamic>{
PlatformType.ANDROID: 'ANDROID',
PlatformType.IOS: 'IOS',
PlatformType.ANDROID_THING: 'ANDROID_THING',
PlatformType.ANY: 'ANY'
};
Action.dart
import 'package:json_annotation/json_annotation.dart';
part 'action.g.dart';
#JsonSerializable()
class Action {
String label;
String url;
Action(this.label,this.url);
factory Action.fromJson(Map<String, dynamic> json) => _$ActionFromJson(json);
Map<String, dynamic> toJson() => _$ActionToJson(this);
}
Action Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'action.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Action _$ActionFromJson(Map<String, dynamic> json) {
return Action(json['label'] as String, json['url'] as String);
}
Map<String, dynamic> _$ActionToJson(Action instance) =>
<String, dynamic>{'label': instance.label, 'url': instance.url};
PlatformType and CardType are enums
Okay turns out I have to decode and encoded string before passing it to firebase.
So code to save the model class to firebase will be like this:
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
var jsonString = json.encode(egluCard);
print(json.decode(jsonString));
cardsDBRef.push().set(json.decode(jsonString))
.then((_){
print('saved!!');
});