How to parse a nested JSON dictionary (map) - json

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"}}

Related

Flutter/Dart: JSON parsing

Is it possible to get a list from json without looping the jsonResponse?
In the sample below, i want to get list of language
targetList = ["Pascal", "Python","SQL"]
{
"eBooks":[
{
"language":"Pascal",
"edition":"third"
},
{
"language":"Python",
"edition":"four"
},
{
"language":"SQL",
"edition":"second"
}
]
}
void main() {
String json = "{\"eBooks\":[{\"language\":\"Pascal\",\"edition\":\"third\"},{\"language\":\"Python\",\"edition\":\"four\"},{\"language\":\"SQL\",\"edition\":\"second\"}]}";
JsonData result = JsonData.fromJson(jsonDecode(json));
List<String> targetList = [];
for(var book in result.eBooks!) {
targetList.add(book.language!);
}
print(targetList); // [Pascal, Python, SQL]
}
Json Object:
class JsonData {
List<EBooks>? _eBooks;
List<EBooks>? get eBooks => _eBooks;
JsonData({List<EBooks>? eBooks}) {
_eBooks = eBooks;
}
JsonData.fromJson(dynamic json) {
if (json["eBooks"] != null) {
_eBooks = [];
json["eBooks"].forEach((v) {
_eBooks?.add(EBooks.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
var map = <String, dynamic>{};
if (_eBooks != null) {
map["eBooks"] = _eBooks?.map((v) => v.toJson()).toList();
}
return map;
}
}
class EBooks {
String? _language;
String? _edition;
String? get language => _language;
String? get edition => _edition;
EBooks({String? language, String? edition}) {
_language = language;
_edition = edition;
}
EBooks.fromJson(dynamic json) {
_language = json["language"];
_edition = json["edition"];
}
Map<String, dynamic> toJson() {
var map = <String, dynamic>{};
map["language"] = _language;
map["edition"] = _edition;
return map;
}
}
Have a look at the example below
void main() {
var map = {
"eBooks": [
{"language": "Pascal", "edition": "third"},
{"language": "Python", "edition": "four"},
{"language": "SQL", "edition": "second"}
]
};
var lst = map["eBooks"].map((e) => e["language"]).toList();
print(lst.length);
lst.forEach((l) {
print(l);
});
}
First you need to create a model class. Then we see a second value in which the other variables are kept. Then you can access the list in it by creating an object from this class. You can translate your model to JSON to Dart language through these sites. jsontodart jsontodart2
class TargetList {
List<EBooks> eBooks;
TargetList({this.eBooks});
TargetList.fromJson(Map<String, dynamic> json) {
if (json['eBooks'] != null) {
eBooks = new List<EBooks>();
json['eBooks'].forEach((v) {
eBooks.add(new EBooks.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.eBooks != null) {
data['eBooks'] = this.eBooks.map((v) => v.toJson()).toList();
}
return data;
}
}
class EBooks {
String language;
String edition;
EBooks({this.language, this.edition});
EBooks.fromJson(Map<String, dynamic> json) {
language = json['language'];
edition = json['edition'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['language'] = this.language;
data['edition'] = this.edition;
return data;
}
}

How to concat two JSONObject with same key of a JSONArray in flutter

The JSON request has been split into two json object in the DataList JSONArray , because data is too large, how do i combine these two objects before i can decompress and get the values . Iam new to dart and flutter , any help would be appreciated. Thank you.
"DataList": [
{
"Data": "compressedata"
},
{
"Data": "compressedData"
}
],
here is what i have tried
class ResponseList {
List<DataList> dataList;
ResponseList({ this.DataList});
ResponseList.fromJson(Map<String, dynamic> json) {
if (json['DataList'] != null) {
DataList = new List<DataList>();
json['DataList'].forEach((v) {
dataList.add(new DataList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = new Map<String, dynamic>();
if (this.DataList != null) {
map['DataList'] = this.dataList.map((v) => v.toJson()).toList();
}
return map;
}
}
class DataList {
String data;
DataList({this.data});
DataList.fromJson(Map<String, dynamic> json) {
data = json['Data'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = new Map<String, dynamic>();
map['Data'] = this.data;
return map;
}
}
Using the Datalist array you can do the following:
var dataList = [
{"Data": "compressedata"},
{"Data": "compressedData"}
];
var compressedData = dataList
.map((item) => item["Data"])
.reduce((value, element) => value + element);
print(compressedData); // compressedatacompressedData

Error: type 'String' is not a subtype of type 'List<dynamic>'

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

flutter : nested json parsing list

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

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