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.
Related
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;
}
I want to fetch dat form some API and parse its data to model.
MyModel:
class SetupIdeaModel {
String id;
String userId;
String typeIdea = "Implemented Idea";
String category; //Or Industry
String experienceYear;
String experienceMonth;
String ideaHeadline;
String ideaText;
Map timeline = {
"timelineType": "date",
"details": null,
};
List documents = [];
Map uploadVideo;
String location;
String estimatedPeople;
Map whitePaper;
bool needServiceProvider = false;
bool needInvestor = true;
}
}
and I fetch data from the API with the getIdeaList method:
getIdeaList method
Future getIdeaList(String token) async {
Response response = await APIRequest().get(
myUrl: "$baseUrl/innovator/idea/list",
token: token,
);
//Parsing ideaList to SetupIdeaModel
ideas = List();
try {
(response.data as List).forEach((element) {
SetupIdeaModel idea = new SetupIdeaModel();
var months = int.parse(element["industryExperienceInMonth"]);
var year = (months / 12).floor();
var remainderMonths = months % 12;
print("$year year and $remainderMonths months");
idea.id = element["_id"];
idea.userId = element["userId"];
idea.typeIdea = element["ideaType"];
idea.category = element["industry"];
idea.experienceYear = year.toString();
idea.experienceMonth = remainderMonths.toString();
idea.ideaHeadline = element["headline"];
idea.ideaText = element["idea"];
idea.estimatedPeople = element["estimatedPeople"].toString();
print("Documents ${element["uploadDocuments"]}");
idea.location = element["targetAudience"];
idea.documents = element["uploadDocuments"];
// idea.timeline = element["timeline"];
// idea.uploadVideo = element["uploadVideo"];
ideas.add(idea);
});
} catch (e) {
print("Error: $e");
}
print("ideas $ideas");
notifyListeners();
}
Everything is OK but When I add one of these line:
idea.documents = element["uploadDocuments"];
idea.timeline = element["timeline"];
idea.uploadVideo = element["uploadVideo"];
I have got the error.
The data comes for the API is like this:
[
{
"industryExperienceInMonth":30,
"estimatedPeople":200,
"needServiceProvider":true,
"needInvestor":true,
"_id":5fcc681fc5b4260011810112,
"userId":5fb6650eacc60d0011910a9b,
"ideaType":"Implemented Idea",
"industry":"Technalogy",
"headline":"IDea headline",
"idea":"This is aobut your idea",
"timeline":{
"timelineType":"date",
"details":{
"date":Dec 6,
2020
}
},
"uploadDocuments":[
{
"_id":5fcc6804c5b4260011810110,
"uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/document/741333-beats_by_dre-wallpaper-1366x768.jpg
}
],
"uploadVideo":{
"_id":5fcc681ac5b4260011810111,
"uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/video/588700-beats_by_dre-wallpaper-1366x768.jpg
},
"targetAudience":"heart",
"__v":0
}
]
I'm using Dio package.
The documents in the model is a list and the uploadDocuments the come form API is a list too. But Why I got this error.
Your JSON data has some syntax errors that's why it's not working. All the UIDs and URLs should be in string format and you should Serializing JSON inside model classes. see also
I have fix some error in your code and did some improvement :
Future getIdeaList(String token) async {
List<SetupIdeaModel> setupIdeaModel = List();
try {
Response response = await APIRequest().get(
myUrl: "$baseUrl/innovator/idea/list",
token: token,
);
if (response.statusCode == 200) {
List<SetupIdeaModel> apiData = (json.decode(utf8.decode(response.data)) as List)
.map((data) => new SetupIdeaModel.fromJson(data))
.toList();
setupIdeaModel.addAll(apiData);
}
} catch (e) {
print("Error: $e");
}
}
This is the model class :
class SetupIdeaModel {
int industryExperienceInMonth;
int estimatedPeople;
bool needServiceProvider;
bool needInvestor;
String sId;
String userId;
String ideaType;
String industry;
String headline;
String idea;
Timeline timeline;
List<UploadDocuments> uploadDocuments;
UploadDocuments uploadVideo;
String targetAudience;
int iV;
SetupIdeaModel(
{this.industryExperienceInMonth,
this.estimatedPeople,
this.needServiceProvider,
this.needInvestor,
this.sId,
this.userId,
this.ideaType,
this.industry,
this.headline,
this.idea,
this.timeline,
this.uploadDocuments,
this.uploadVideo,
this.targetAudience,
this.iV});
SetupIdeaModel.fromJson(Map<String, dynamic> json) {
industryExperienceInMonth = json['industryExperienceInMonth'];
estimatedPeople = json['estimatedPeople'];
needServiceProvider = json['needServiceProvider'];
needInvestor = json['needInvestor'];
sId = json['_id'];
userId = json['userId'];
ideaType = json['ideaType'];
industry = json['industry'];
headline = json['headline'];
idea = json['idea'];
timeline = json['timeline'] != null
? new Timeline.fromJson(json['timeline'])
: null;
if (json['uploadDocuments'] != null) {
uploadDocuments = new List<UploadDocuments>();
json['uploadDocuments'].forEach((v) {
uploadDocuments.add(new UploadDocuments.fromJson(v));
});
}
uploadVideo = json['uploadVideo'] != null
? new UploadDocuments.fromJson(json['uploadVideo'])
: null;
targetAudience = json['targetAudience'];
iV = json['__v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['industryExperienceInMonth'] = this.industryExperienceInMonth;
data['estimatedPeople'] = this.estimatedPeople;
data['needServiceProvider'] = this.needServiceProvider;
data['needInvestor'] = this.needInvestor;
data['_id'] = this.sId;
data['userId'] = this.userId;
data['ideaType'] = this.ideaType;
data['industry'] = this.industry;
data['headline'] = this.headline;
data['idea'] = this.idea;
if (this.timeline != null) {
data['timeline'] = this.timeline.toJson();
}
if (this.uploadDocuments != null) {
data['uploadDocuments'] =
this.uploadDocuments.map((v) => v.toJson()).toList();
}
if (this.uploadVideo != null) {
data['uploadVideo'] = this.uploadVideo.toJson();
}
data['targetAudience'] = this.targetAudience;
data['__v'] = this.iV;
return data;
}
}
class Timeline {
String timelineType;
Details details;
Timeline({this.timelineType, this.details});
Timeline.fromJson(Map<String, dynamic> json) {
timelineType = json['timelineType'];
details =
json['details'] != null ? new Details.fromJson(json['details']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['timelineType'] = this.timelineType;
if (this.details != null) {
data['details'] = this.details.toJson();
}
return data;
}
}
class Details {
String date;
Details({this.date});
Details.fromJson(Map<String, dynamic> json) {
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
return data;
}
}
class UploadDocuments {
String sId;
String uriPath;
UploadDocuments({this.sId, this.uriPath});
UploadDocuments.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
uriPath = json['uriPath'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['uriPath'] = this.uriPath;
return data;
}
}
hy we have a radio server with the followoing json file
{
"icestats":{
"admin":"icemaster#localhost",
"host":"online.localhost.be",
"location":"Earth",
"server_id":"Icecast 2.4.4",
"server_start":"Sun, 30 Aug 2020 10:50:52 +0200",
"server_start_iso8601":"2020-08-30T10:50:52+0200",
"source":[
{
"audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
"bitrate":320,
"genre":"oldies",
"ice-bitrate":320,
"ice-channels":2,
"ice-samplerate":44100,
"listener_peak":0,
"listeners":0,
"listenurl":"http://127.0.0.1:8000/mp3_320",
"server_description":"Very Oldies!",
"server_name":"loclahost",
"server_type":"audio/mpeg",
"server_url":"https://127.0.0.1:8000",
"stream_start":"Sun, 30 Aug 2020 13:45:16 +0200",
"stream_start_iso8601":"2020-08-30T13:45:16+0200",
"title":"1951: Four Knights - I Love The Sunshine Of Your Smile",
"dummy":null
},
{
"audio_bitrate":320000,
"audio_channels":2,
"audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
"audio_samplerate":44100,
"bitrate":320,
"genre":"oldies",
"ice-bitrate":320,
"ice-channels":2,
"ice-samplerate":44100,
"listener_peak":0,
"listeners":0,
"listenurl":"http://127.0.0.1:8000/ogg_320",
"server_description":"Very Oldies!",
"server_name":"localhost",
"server_type":"application/ogg",
"server_url":"https://127.0.0.1:8000",
"stream_start":"Sun, 30 Aug 2020 13:45:16 +0200",
"stream_start_iso8601":"2020-08-30T13:45:16+0200",
"subtype":"Vorbis",
"dummy":null
}
]
}
}
if io parse this with this model i get the error 'unexpected charcater at 1'
class Autogenerated {
Icestats icestats;
Autogenerated({this.icestats});
Autogenerated.fromJson(Map<String, dynamic> json) {
icestats = json['icestats'] != null
? new Icestats.fromJson(json['icestats'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.icestats != null) {
data['icestats'] = this.icestats.toJson();
}
return data;
}
}
class Icestats {
String admin;
String host;
String location;
String serverId;
String serverStart;
String serverStartIso8601;
List<Source> source;
Icestats(
{this.admin,
this.host,
this.location,
this.serverId,
this.serverStart,
this.serverStartIso8601,
this.source});
Icestats.fromJson(Map<String, dynamic> json) {
admin = json['admin'];
host = json['host'];
location = json['location'];
serverId = json['server_id'];
serverStart = json['server_start'];
serverStartIso8601 = json['server_start_iso8601'];
if (json['source'] != null) {
source = new List<Source>();
json['source'].forEach((v) {
source.add(new Source.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['admin'] = this.admin;
data['host'] = this.host;
data['location'] = this.location;
data['server_id'] = this.serverId;
data['server_start'] = this.serverStart;
data['server_start_iso8601'] = this.serverStartIso8601;
if (this.source != null) {
data['source'] = this.source.map((v) => v.toJson()).toList();
}
return data;
}
}
class Source {
String audioInfo;
int bitrate;
String genre;
int iceBitrate;
int iceChannels;
int iceSamplerate;
int listenerPeak;
int listeners;
String listenurl;
String serverDescription;
String serverName;
String serverType;
String serverUrl;
String streamStart;
String streamStartIso8601;
String title;
Null dummy;
int audioBitrate;
int audioChannels;
int audioSamplerate;
String subtype;
Source(
{this.audioInfo,
this.bitrate,
this.genre,
this.iceBitrate,
this.iceChannels,
this.iceSamplerate,
this.listenerPeak,
this.listeners,
this.listenurl,
this.serverDescription,
this.serverName,
this.serverType,
this.serverUrl,
this.streamStart,
this.streamStartIso8601,
this.title,
this.dummy,
this.audioBitrate,
this.audioChannels,
this.audioSamplerate,
this.subtype});
Source.fromJson(Map<String, dynamic> json) {
audioInfo = json['audio_info'];
bitrate = json['bitrate'];
genre = json['genre'];
iceBitrate = json['ice-bitrate'];
iceChannels = json['ice-channels'];
iceSamplerate = json['ice-samplerate'];
listenerPeak = json['listener_peak'];
listeners = json['listeners'];
listenurl = json['listenurl'];
serverDescription = json['server_description'];
serverName = json['server_name'];
serverType = json['server_type'];
serverUrl = json['server_url'];
streamStart = json['stream_start'];
streamStartIso8601 = json['stream_start_iso8601'];
title = json['title'];
dummy = json['dummy'];
audioBitrate = json['audio_bitrate'];
audioChannels = json['audio_channels'];
audioSamplerate = json['audio_samplerate'];
subtype = json['subtype'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['audio_info'] = this.audioInfo;
data['bitrate'] = this.bitrate;
data['genre'] = this.genre;
data['ice-bitrate'] = this.iceBitrate;
data['ice-channels'] = this.iceChannels;
data['ice-samplerate'] = this.iceSamplerate;
data['listener_peak'] = this.listenerPeak;
data['listeners'] = this.listeners;
data['listenurl'] = this.listenurl;
data['server_description'] = this.serverDescription;
data['server_name'] = this.serverName;
data['server_type'] = this.serverType;
data['server_url'] = this.serverUrl;
data['stream_start'] = this.streamStart;
data['stream_start_iso8601'] = this.streamStartIso8601;
data['title'] = this.title;
data['dummy'] = this.dummy;
data['audio_bitrate'] = this.audioBitrate;
data['audio_channels'] = this.audioChannels;
data['audio_samplerate'] = this.audioSamplerate;
data['subtype'] = this.subtype;
return data;
}
}
the code i have used i pretty simple this is the code i have used.
if i parse the same code with a simple xml structure this works but with the icecast parsing this does not succeed.
please advice me
var JsonData = 'http://127.0.0.1:8000/status-json.xsl';
var parsedJson = json.decode(JsonData);
var title = Source.fromJson(parsedJson);
is the json formatting of the icecast server incorrect ? it starts with a {
update 1
class User {
String title;
User(Map<String, dynamic> data){
title = data['title'];
}
}
Future<Source> fetchData() async{
var jsonData = 'http://online.doobeedoo.be:8000/status-json.xsl';
final response =
await http.get(jsonData); //wacht to de data is ontvangen (200)
if(response.statusCode == 200)
{
var parsedJson = json.decode(response.body); //parsen van response
var user = User(parsedJson);
return('${user.title}'); //error here (A value of type 'String' can't be returned from function 'fetchData' because it has a return type of 'Future<Source>'.)
}
else
{
throw Exception('Failed to load status.json response file');
}
}
Use the http package to make a request to your server and retrieve a response. Then parse the JSON the way your currently have it. You're currently parsing a String URL. Not a JSON.
import 'package:http/http.dart' as http;
var url = 'http://127.0.0.1:8000/status-json.xsl';
var response = await http.get(url);//Actually get the data at the URL
var parsedJson = json.decode(response.body);//Parse the response
var title = Source.fromJson(parsedJson);
I am trying to read a JSON code which is compatible with a Swift program into a flutter app. The structure is like this:
{
"tagDict" : {
"abc" : {
"helpHdr" : "short text1",
"helpText" : "long text1"
},
"def" : {
"helpHdr" : "short text2",
"helpText" : "long text2"
}
}
}
This creates in Swift a dictionary and shall create a map in Dart of the type {key : {helpHdr, helpText}}. A variable based on this should enable label = myVariable[tag].helpHdr, or staying with the example label = myVariable["abc"].helpHdr should assign "short text1" to label
To parse nested arrays I am using this, however, no clue how to transfer this to such a nested map.
class MyClass {
List<MySubClass> myArray;
MyClass({
this.myArray,
});
factory MyClass.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['myArray'] as List;
List<MySubClass> listObject = list.map((i) => MySubClass.fromJson(i)).toList();
return new MyClass(
myArray: listObject,
);
}
}
class MySubClass {
int id;
String text1;
String text2;
MySubClass({
this.id,
this.text1,
this.text2,
});
factory MySubClass.fromJson(Map<String, dynamic> parsedJson){
return new MySubClass(
id: parsedJson['id'],
text1: parsedJson['text1'],
text2: parsedJson['text2'],
);
}
}
If I'm correct you want to parse your json into Data class object. If that's right then you can try this
void main() {
List<MyClass> myClassList = new List<MyClass>();
Map map = {
"tagDict": {
"abc": {"helpHdr": "short text1", "helpText": "long text1"},
"def": {"helpHdr": "short text2", "helpText": "long text2"}
}
};
map['tagDict'].forEach((key, value) {
value['id'] = key;
myClassList.add(MyClass.fromJson(value));
});
myClassList.forEach((myClass) {
print(myClass.id);
print(myClass.helpHdr);
print(myClass.helpText);
print("--------------------\n");
});
}
class MyClass {
String id;
String helpHdr;
String helpText;
MyClass({this.id, this.helpHdr, this.helpText});
MyClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
This is the Output:
abc
short text1
long text1
--------------------
def
short text2
long text2
--------------------
class TagRes {
TagDict tagDict;
TagRes({this.tagDict});
TagRes.fromJson(Map<String, dynamic> json) {
tagDict =
json['tagDict'] != null ? new TagDict.fromJson(json['tagDict']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.tagDict != null) {
data['tagDict'] = this.tagDict.toJson();
}
return data;
}
}
class TagDict {
Abc abc;
Abc def;
TagDict({this.abc, this.def});
TagDict.fromJson(Map<String, dynamic> json) {
abc = json['abc'] != null ? new Abc.fromJson(json['abc']) : null;
def = json['def'] != null ? new Abc.fromJson(json['def']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.abc != null) {
data['abc'] = this.abc.toJson();
}
if (this.def != null) {
data['def'] = this.def.toJson();
}
return data;
}
}
class Abc {
String helpHdr;
String helpText;
Abc({this.helpHdr, this.helpText});
Abc.fromJson(Map<String, dynamic> json) {
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
Based on Tipu's answer, I came up with the following code which creates the intended dictionary (or map in Dart - why couldn't they stick to standard terminology like arrays etc?!)
class TaskTags {
var tagDict = Map<String, TaskTag>();
TaskTags({
this.tagDict,
});
factory TaskTags.fromJson(Map<String, dynamic> json){
var innerMap = json['tagDict'];
var tagMap = Map<String, TaskTag>();
innerMap.forEach((key, value) {
tagMap.addAll({key: TaskTag.fromJson(value)});
});
return new TaskTags(
tagDict: tagMap,
);
}
}
class TaskTag {
String helpHdr;
String helpText;
TaskTag({
this.helpHdr,
this.helpText,
});
factory TaskTag.fromJson(Map<String, dynamic> json){
return new TaskTag(
helpHdr: json['helpHdr'],
helpText: json['helpText'],
);
}
}
This creates the following map
{"abc“ : {helpHdr: "short text1", helpText: "long text1"}, "def“ : {helpHdr: "short text2", helpText: "long text2"}}
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;
}
}