How to parse a complex Json value in flutter? - json

I have a JSON which is a combination of simple and complicated structures.Anyhow you can have a look at it.All I want is to get the "playlist_url": value and display it a listview builder.Along with that I want to parse for 2 text values which I am able to do.But the url part is where I am not able to resolve
The JSON structure(it is too long,thats y I have given the link): https://docs.google.com/document/d/1saJN3MQvG55M1ipf42-65Etowi_kW80gkrosU6vBb5o/edit?usp=sharing
The PODO file:
// To parse this JSON data, do
//
// final homePage = homePageFromJson(jsonString);
import 'dart:convert';
HomePage homePageFromJson(String str) => HomePage.fromJson(json.decode(str));
String homePageToJson(HomePage data) => json.encode(data.toJson());
class HomePage {
HomePage({
this.series,
this.homeBanners,
this.liveChannels,
this.publishers,
this.musicCategories,
this.musicPlaylists,
this.movies,
});
List<HomeBanner> series;
List<HomeBanner> homeBanners;
List<LiveChannel> liveChannels;
List<Publisher> publishers;
List<Music> musicCategories;
Music musicPlaylists;
List<HomeBanner> movies;
factory HomePage.fromJson(Map<String, dynamic> json) => HomePage(
series: List<HomeBanner>.from(
json["series"].map((x) => HomeBanner.fromJson(x))),
homeBanners: List<HomeBanner>.from(
json["home_banners"].map((x) => HomeBanner.fromJson(x))),
liveChannels: List<LiveChannel>.from(
json["live_channels"].map((x) => LiveChannel.fromJson(x))),
publishers: List<Publisher>.from(
json["publishers"].map((x) => Publisher.fromJson(x))),
musicCategories: List<Music>.from(
json["music_categories"].map((x) => Music.fromJson(x))),
musicPlaylists: Music.fromJson(json["music_playlists"]),
movies: List<HomeBanner>.from(
json["movies"].map((x) => HomeBanner.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"series": List<dynamic>.from(series.map((x) => x.toJson())),
"home_banners": List<dynamic>.from(homeBanners.map((x) => x.toJson())),
"live_channels":
List<dynamic>.from(liveChannels.map((x) => x.toJson())),
"publishers": List<dynamic>.from(publishers.map((x) => x.toJson())),
"music_categories":
List<dynamic>.from(musicCategories.map((x) => x.toJson())),
"music_playlists": musicPlaylists.toJson(),
"movies": List<dynamic>.from(movies.map((x) => x.toJson())),
};
}
class HomeBanner {
HomeBanner({
this.movieId,
this.title,
this.tags,
this.genres,
this.thumbnail,
this.posterLink,
this.platform,
this.worldwide,
this.createdAt,
this.seriesId,
});
String movieId;
String title;
List<String> tags;
List<String> genres;
List<String> thumbnail;
String posterLink;
Platform platform;
double worldwide;
DateTime createdAt;
String seriesId;
factory HomeBanner.fromJson(Map<String, dynamic> json) => HomeBanner(
movieId: json["movie_id"] == null ? null : json["movie_id"],
title: json["title"],
tags: List<String>.from(json["tags"].map((x) => x)),
genres: List<String>.from(json["genres"].map((x) => x)),
thumbnail: List<String>.from(json["thumbnail"].map((x) => x)),
posterLink: json["poster_link"],
platform: platformValues.map[json["platform"]],
worldwide: json["WORLDWIDE"],
createdAt: DateTime.parse(json["createdAt"]),
seriesId: json["series_id"] == null ? null : json["series_id"],
);
Map<String, dynamic> toJson() => {
"movie_id": movieId == null ? null : movieId,
"title": title,
"tags": List<dynamic>.from(tags.map((x) => x)),
"genres": List<dynamic>.from(genres.map((x) => x)),
"thumbnail": List<dynamic>.from(thumbnail.map((x) => x)),
"poster_link": posterLink,
"platform": platformValues.reverse[platform],
"WORLDWIDE": worldwide,
"createdAt": createdAt.toIso8601String(),
"series_id": seriesId == null ? null : seriesId,
};
}
enum Platform { YOUTUBE, DISCOVERYPLUS }
final platformValues = EnumValues(
{"discoveryplus": Platform.DISCOVERYPLUS, "youtube": Platform.YOUTUBE});
class LiveChannel {
LiveChannel({
this.keyId,
this.postContent,
this.publisherId,
this.publisherName,
this.publisherProfilePic,
this.publisherDesc,
this.downvotesCount,
this.upvotesCount,
});
String keyId;
PostContent postContent;
String publisherId;
String publisherName;
String publisherProfilePic;
String publisherDesc;
int downvotesCount;
int upvotesCount;
factory LiveChannel.fromJson(Map<String, dynamic> json) => LiveChannel(
keyId: json["key_id"],
postContent: PostContent.fromJson(json["post_content"]),
publisherId: json["publisher_id"],
publisherName: json["publisher_name"],
publisherProfilePic: json["publisher_profile_pic"],
publisherDesc: json["publisher_desc"],
downvotesCount: json["downvotes_count"],
upvotesCount: json["upvotes_count"],
);
Map<String, dynamic> toJson() => {
"key_id": keyId,
"post_content": postContent.toJson(),
"publisher_id": publisherId,
"publisher_name": publisherName,
"publisher_profile_pic": publisherProfilePic,
"publisher_desc": publisherDesc,
"downvotes_count": downvotesCount,
"upvotes_count": upvotesCount,
};
}
class PostContent {
PostContent({
this.shortcode,
this.platformVideoLink,
this.caption,
this.description,
});
String shortcode;
String platformVideoLink;
String caption;
String description;
factory PostContent.fromJson(Map<String, dynamic> json) => PostContent(
shortcode: json["shortcode"],
platformVideoLink: json["platform_videoLink"],
caption: json["caption"],
description: json["description"],
);
Map<String, dynamic> toJson() => {
"shortcode": shortcode,
"platform_videoLink": platformVideoLink,
"caption": caption,
"description": description,
};
}
class Music {
Music({
this.id,
this.country,
this.categoryId,
this.categoryName,
this.categoryIcons,
this.playlists,
});
dynamic id;
String country;
String categoryId;
String categoryName;
List<CategoryIcon> categoryIcons;
List<Playlist> playlists;
factory Music.fromJson(Map<String, dynamic> json) => Music(
id: json["_id"],
country: json["country"],
categoryId: json["category_id"],
categoryName: json["category_name"],
categoryIcons: List<CategoryIcon>.from(
json["category_icons"].map((x) => CategoryIcon.fromJson(x))),
playlists: List<Playlist>.from(
json["playlists"].map((x) => Playlist.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"_id": id,
"country": country,
"category_id": categoryId,
"category_name": categoryName,
"category_icons":
List<dynamic>.from(categoryIcons.map((x) => x.toJson())),
"playlists": List<dynamic>.from(playlists.map((x) => x.toJson())),
};
}
class CategoryIcon {
CategoryIcon({
this.height,
this.url,
this.width,
});
int height;
String url;
int width;
factory CategoryIcon.fromJson(Map<String, dynamic> json) => CategoryIcon(
height: json["height"] == null ? null : json["height"],
url: json["url"],
width: json["width"] == null ? null : json["width"],
);
Map<String, dynamic> toJson() => {
"height": height == null ? null : height,
"url": url,
"width": width == null ? null : width,
};
}
class Playlist {
Playlist({
this.playlistName,
this.playlistDescription,
this.playlistUrl,
this.playlistTotalTracks,
this.playlistImages,
this.playlistFollowers,
this.playlistId,
});
String playlistName;
String playlistDescription;
String playlistUrl;
int playlistTotalTracks;
List<CategoryIcon> playlistImages;
int playlistFollowers;
String playlistId;
factory Playlist.fromJson(Map<String, dynamic> json) => Playlist(
playlistName: json["playlist_name"],
playlistDescription: json["playlist_description"],
playlistUrl: json["playlist_url"],
playlistTotalTracks: json["playlist_total_tracks"],
playlistImages: List<CategoryIcon>.from(
json["playlist_images"].map((x) => CategoryIcon.fromJson(x))),
playlistFollowers: json["playlist_followers"],
playlistId: json["playlist_id"],
);
Map<String, dynamic> toJson() => {
"playlist_name": playlistName,
"playlist_description": playlistDescription,
"playlist_url": playlistUrl,
"playlist_total_tracks": playlistTotalTracks,
"playlist_images":
List<dynamic>.from(playlistImages.map((x) => x.toJson())),
"playlist_followers": playlistFollowers,
"playlist_id": playlistId,
};
}
class Publisher {
Publisher({
this.platform,
this.username,
this.fullName,
this.profilePicUrl,
this.content,
this.keyId,
});
Platform platform;
String username;
String fullName;
String profilePicUrl;
Content content;
String keyId;
factory Publisher.fromJson(Map<String, dynamic> json) => Publisher(
platform: platformValues.map[json["platform"]],
username: json["username"],
fullName: json["full_name"],
profilePicUrl: json["profile_pic_url"],
content: Content.fromJson(json["content"]),
keyId: json["key_id"],
);
Map<String, dynamic> toJson() => {
"platform": platformValues.reverse[platform],
"username": username,
"full_name": fullName,
"profile_pic_url": profilePicUrl,
"content": content.toJson(),
"key_id": keyId,
};
}
class Content {
Content({
this.description,
});
String description;
factory Content.fromJson(Map<String, dynamic> json) => Content(
description: json["description"],
);
Map<String, dynamic> toJson() => {
"description": description,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
The class called services where I am trying to parse the playlist_url.I am able to parse the playlist name and the number of videos of it(the count of it)
class Services {
static const String url =
"https://livetvapi.apyhi.com/api/v2/home?pageLocation=home&countries=IN&app_version=13&"
"user_id=44edc2c905ae163f&package_id=livetv.movies.freemovies.watchtv.tvshows&os_platform=android";
static Future<List<String>> loadDataForPlaylistDetailsForButtomTitle() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is there");
final homePage = homePageFromJson(res.body);
Playlist playListObject = new Playlist();
List<String> lst_names = [];
for (playListObject in homePage.musicPlaylists.playlists)
lst_names.add(playListObject.playlistName);
print("Buttom titles");
print(lst_names);
return lst_names;
} else {
print("no response");
return null;
}
}
static Future<List<String>> loadDataForPlaylistDetailsForCount() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is there");
final homePage = homePageFromJson(res.body);
Playlist playListObject = new Playlist();
List<String> lst_names = [];
for (playListObject in homePage.musicPlaylists.playlists)
lst_names.add(playListObject.playlistTotalTracks.toString());
print("count");
print(lst_names);
return lst_names;
} else {
print("no response");
return null;
}
}
static Future<List<Playlist>> loadDataForPlaylistDetailsForImageUrl() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is there");
final homePage = homePageFromJson(res.body);
Music musicObject = new Music();
List<Playlist> playlistObj = homePage.musicPlaylists.playlists;
print("category icon object returned");
return playlistObj;
} else {
print("no response");
return null;
}
}
}
This is the main file where I am trying to display in listView.First the data is loaded in initstate and then stored in arrays.But for the last one (the url stuff)I tried with the object it self as things became complicated
#override
void initState() {
// TODO: implement initState
super.initState();
Services.loadDataForPlaylistDetailsForButtomTitle().then((playListNames) {
setState(() {
_playListNames = playListNames ;
});
});
Services.loadDataForPlaylistDetailsForButtomTitle().then((playListCount) {
setState(() {
_playListtotalTracks = playListCount ;
});
});
Services.loadDataForPlaylistDetailsForImageUrl().then((objUrl) {
setState(() {
_obj = objUrl ;
});
});
}
The code for listView Builder:
Container(
height: MediaQuery.of(context).size.height * 0.41,
color: Colors.black,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: _playListImageUrls.length,
itemBuilder: (BuildContext context, int index) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
height: MediaQuery.of(context).size.height * 0.34,
child: PhysicalModel(
clipBehavior: Clip.antiAliasWithSaveLayer,
color: Colors.black,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.only(
topRight: Radius.circular(35),
bottomRight: Radius.circular(35)),
child: FadeInImage.assetNetwork(
width: MediaQuery.of(context).size.width * 0.285,
image: _obj[index].playlistImages[index].url,
placeholder: cupertinoActivityIndicator,
fit: BoxFit.fill,
),
),
),
Container(
margin: EdgeInsets.fromLTRB(15, 15, 0, 0),
height: MediaQuery.of(context).size.height * 0.03,
child: Text(
_playListNames[index],
style: TextStyle(color: Colors.white),
)),
Container(
margin: EdgeInsets.fromLTRB(15, 0, 0, 0),
height: MediaQuery.of(context).size.height * 0.02,
child: Text(
_playListtotalTracks[index],
style: TextStyle(color: Colors.white),
))
],
),
),
),
Also I find myself repeating this structures many times.Any suggestions to improvise would be equally welcomed.

I have finally found the solution.The whole point where I was doing the mistake was assuming things as a list of object,rather it was a list of list of single object.
The following modifications were made:
In service file
static Future<List<String>> loadDataForPlaylistDetailsForImageUrl() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
print("response is thereeeeeeeee");
final homePage = homePageFromJson(res.body);
Playlist playListObject = new Playlist();
List<String> urlList = [];
List<dynamic> lst_names = [];
for (playListObject in homePage.musicPlaylists.playlists) {
lst_names.add(playListObject.playlistImages);
print(lst_names);
}
//lst_names=
print("objjjjjjjjjjjjjjjjjjjj");
for (var listobj in lst_names) {
for (var obj in listobj) {
print(obj.url.toString());
urlList.add(obj.url.toString());
}
}
return urlList;
} else {
print("no response");
return null;
}
}
Also in main file:
FadeInImage.assetNetwork(
width: MediaQuery.of(context).size.width * 0.285,
image: _musicPlaylistImgUrlList[index],
//_categoryIconfor[index].url,
//_obj[index].playlistImages[index].url,
placeholder: cupertinoActivityIndicator,
fit: BoxFit.none,
),

Related

How can i pass this complex Json MAP Data into flutter Listview

i am new to flutter, and i meet this API with complex "MAP" json. What i want is to display the list of countries with their details in flutter listview, How can i achieve that? Most of answers explain about "LIST" json.
{
"status": "Request is successful",
"message": null,
"data": {
"page": 1,
"last_page": 125,
"page_size": 2,
"countries": [
{
"id": "1",
"attributes": {
"name": "Grenada",
"code": "GD",
"subregion": "Caribbean",
"flag": "https://flagcdn.com/gd.svg",
"postalcode": "",
"latitude": "12.11666666",
"longitude": "-61.66666666",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
},
{
"id": "2",
"attributes": {
"name": "Malaysia",
"code": "MY",
"subregion": "South-Eastern Asia",
"flag": "https://flagcdn.com/my.svg",
"postalcode": "^(\\d{5})$",
"latitude": "2.5",
"longitude": "112.5",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
}
]
}
}
I found this GitHub project with these files json, modelClass Mainclass which relate with the concept but mine is has got one extra braces (map) so i do not know how to achieve the goal.
if there any suggestion or best way to code please help me.
this is how they created in model class but, but it does not work with me.
class Product {
final List<Result> results;
Product({this.results});
factory Product.fromJson(Map<String, dynamic> data) {
var list = data['data']['result'] as List;
List<Result> resultList = list.map((e) => Result.fromJson(e)).toList();
return Product(
results: resultList,
);
}
}
what i have done is
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var data_from_link;
getData() async {
final String link = 'myurl';
data_from_link = await http.get(Uri.parse(link), headers: {"Accept": "application/json"});
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
return ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
)
);
}
}
You can create two classes for Country and Attribute
class Country {
const Country({required this.id, required this.attributes});
/// Creates a Country from Json map
factory Country.fromJson(Map<String, dynamic> json) => Country(
id: json['id'] as String,
attribute:
Attribute.fromJson(json['attributes'] as Map<String, dynamic>),
);
/// A description for id
final String id;
final Attribute attributes;
}
class Attribute {
const Attribute({
required this.name,
required this.code,
required this.createdAt,
required this.updatedAt,
});
/// Creates a Attribute from Json map
factory Attribute.fromJson(Map<String, dynamic> json) => Attribute(
name: json['name'] as String,
code: json['code'] as String,
createdAt: DateTime.parse(json['createdAt'] as String),
updatedAt: DateTime.parse(json['updatedAt'] as String),
);
final String name;
final String code;
final DateTime createdAt;
final DateTime updatedAt;
}
when decoding:
final res = jsonDecode(json) as Map<String, dynamic>;
final List<Country> list = (res['data']['countries'] as
List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
Thank you but how can i print or call data from country attribute
after decoding because when i try something like Print
(list.country.attribute.name) . I fail. My goal is to display on
Listview
You can use it like this:
ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list[i].attributes.name,
),
subtitle: Text(list[i].attributes.code),
)),
UPDATE
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late Future<List<Country>> futureList;
Future<List<Country>?> getData() async {
final String link = 'yoururl';
final res = await http
.get(Uri.parse(link), headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final List<Country> list = (res['data']['countries'] as List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
return list;
} else {
throw Exception('Failed to fetch data');
}
}
#override
void initState() {
super.initState();
futureList = getData();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: futureList,
builder: (context, snapshot) {
if (snapshot.hasData) {
final list = snapshot.data;
return ListView.builder(
itemCount: list!.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
),
);
} else if (snapshot.hasError) {
return const Text('error fetching data');
}
return const CircularProgressIndicator();
},
);
}
}

showing key along side data json

Hi I have a dynamic json the details in it changes in every product so I wanna show keys along side their corresponding data
any example would be great I am struggling with this. sample json in appDetails wanna show all the keys like systemoverview,benefits, mainFeatures and their data.
In next product it will be changed but appdetails will remain same.
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MaterialApp(home: TestScreen()));
}
class TestScreen extends StatefulWidget {
const TestScreen({Key? key}) : super(key: key);
#override
State<TestScreen> createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
List<AppDetails>? details = [];
final Map<String, dynamic> json = {
"name": "TestingApp",
"category": "Production",
"subcategory": "Productivity",
"imageUrl": "Testing-Banner.jpg",
"logo": "PI.png",
"description": "Testing is an application for easy & effective Inspection",
"appDetails": [
{
"systemOverview": "https:url.com",
"multiDeviceSupport": [
{"item1": "Multi-Device"},
{"item2": "Multi-Lingual"},
{"item3": "Multi-Database"}
],
"mainFeatures": [
{"feature1": "Testing"},
{"feature2": "Ease"},
{"feature3": "Select failure "}
],
"benefits": [
{"benfits1": "Easy & quick solution "},
{"benefits2": "Go paperless "},
personnel’s"}
]
}
]
};
#override
void initState() {
super.initState();
final data = AppDetailModel.fromJson(json);
details = data.appDetails;
List<AppDetails>? parseCategorizedBooksJson(Map<String, dynamic> json) => [
for (var detai in json.values)
for (var de in detai) AppDetails.fromJson(de)
];
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.blue,
title: const Text('Home'),
),
body: SizedBox(
child: ListView.builder(
itemCount: details?.length,
itemBuilder: (context, index) {
final detail = details?[index];
return buildProduct(detail);
},
),
),
);
}
}
Widget buildProduct(AppDetails? detail) => Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: (detail?.benefits ?? []).map((e) {
final index = (detail?.benefits ?? []).indexOf(e);
return Row(
children: [
SizedBox(width: 20, child: Text('${index + 1}.')),
Text('${e.label}'),
],
);
}).toList(),
),
);
class AppDetailModel {
String? name;
String? category;
String? subcategory;
String? imageUrl;
String? logo;
String? description;
List<AppDetails>? appDetails;
AppDetailModel(
{this.name,
this.category,
this.subcategory,
this.imageUrl,
this.logo,
this.description,
this.appDetails});
AppDetailModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
category = json['category'];
subcategory = json['subcategory'];
imageUrl = json['imageUrl'];
logo = json['logo'];
description = json['description'];
if (json['appDetails'] != null) {
appDetails = <AppDetails>[];
json['appDetails'].forEach((v) {
appDetails!.add(AppDetails.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['category'] = category;
data['subcategory'] = subcategory;
data['imageUrl'] = imageUrl;
data['logo'] = logo;
data['description'] = description;
if (appDetails != null) {
data['appDetails'] = appDetails!.map((v) => v.toJson()).toList();
}
return data;
}
}
class AppDetails {
String? systemOverview;
List<Label>? multiDeviceSupport;
List<Label>? mainFeatures;
List<Label>? benefits;
AppDetails(
{this.systemOverview,
this.multiDeviceSupport,
this.mainFeatures,
this.benefits});
AppDetails.fromJson(Map<String, dynamic> json) {
systemOverview = json['systemOverview'];
if (json['multiDeviceSupport'] != null) {
multiDeviceSupport = <Label>[];
json['multiDeviceSupport'].forEach((v) {
multiDeviceSupport!.add(Label.fromJson(v));
});
}
if (json['mainFeatures'] != null) {
mainFeatures = <Label>[];
json['mainFeatures'].forEach((v) {
mainFeatures!.add(Label.fromJson(v));
});
}
if (json['benefits'] != null) {
benefits = <Label>[];
json['benefits'].forEach((v) {
benefits!.add(Label.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['systemOverview'] = systemOverview;
if (multiDeviceSupport != null) {
data['multiDeviceSupport'] =
multiDeviceSupport!.map((v) => v.toJson()).toList();
}
if (mainFeatures != null) {
data['mainFeatures'] = mainFeatures!.map((v) => v.toJson()).toList();
}
if (benefits != null) {
data['benefits'] = benefits!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Label {
String? label;
Label({this.label});
Label.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['label'] = label;
return data;
}
}
```
currently What I am doing right now
so taking your example:
final map = {
"appDetails": [
{
"systemOverview": "https:url.com",
"multiDeviceSupport": [
{"label": "Multi-Device"}
],
"mainFeatures": [
{"label": "Testing"}
],
"benefits": [
{"label": "Easy & quick solution "},
{"label": "Go paperless "}
]
}
]
};
we can get both the key and value using the entries like this:
map!["appDetails"]![0].entries.forEach((e) {
print("${e.key}, ${e.value}");
});
This code will print this result:
systemOverview, https:url.com
multiDeviceSupport, [{label: Multi-Device}]
mainFeatures, [{label: Testing}]
benefits, [{label: Easy & quick solution }, {label: Go paperless }]
it will print the key along with it's value, you can use this sample to achieve your result.
print all keys of JSON data
var data = convert.jsonDecode(response.body);
print(data.keys.toList());
you can do somthing like this
Column(children:
data['appDetails']
.map(
(system) => Column(
children: system.entries
.map<Widget>(
(systemeEntry) => systemeEntry.value is String
? Row(
children: [
Text("${systemeEntry.key}: "),
Expanded(child: Text(systemeEntry.value)),
],
)
: systemeEntry.value is List
? Row(
children: [
Text(" ${systemeEntry.key} => "),
Expanded(
child: Column(
children:
systemeEntry.value is List
? systemeEntry.value
.map<Widget>(
(detail) => Column(
children: [
...detail
.entries
.map(
(detailEntry) =>
Row(
children: [
Text(" ${detailEntry.key}: "),
Text(detailEntry.value),
]),
)
.toList()
]),
)
.toList()
: [const SizedBox()],
),
)
],
)
: const SizedBox(),
)
.toList(),
),
)
.toList(),
)

How to display in widget the complex JSON using flutter?

My problem is i don't know how to display the Object inside the Object of JSON.
But i already display the Outer Object like name, usermae etc. And i want to display the object inside the Address and Geo. Im new to JSON and flutter please guide me
i read this but i dont know what i need here
the code is from here
JSON OUTPUT json is from here
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
]
MODEL
i generate my model in here
import 'dart:convert';
List<UserModel> userModelFromJson(String str) =>
List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
UserModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({
this.street,
this.suite,
this.city,
this.zipcode,
this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
String lat;
String lng;
Geo({
this.lat,
this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
String name;
String catchPhrase;
String bs;
Company({
this.name,
this.catchPhrase,
this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
Services.dart
class Services {
static const String url = 'https://jsonplaceholder.typicode.com/users';
static Future<List<UserModel>> getUsers() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
final List<UserModel> users = userModelFromJson(response.body);
return users;
} else {
return List<UserModel>();
}
} catch (e) {
return List<UserModel>();
}
}
}
HomeView.dart
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text(user.name),
subtitle: Text(user.email),
trailing: Text(user.phone),
),
],
);
},
),
),
);
}
}
Thank you for your kindness
The model that you create is correct, you have (Good habit) only to check the objects inside your model before you parse them
UserModel.fromJson(Map<String, dynamic> json) {
// ...
address =
json['address'] != null ? new Address.fromJson(json['address']) : null;
company =
json['company'] != null ? new Company.fromJson(json['company']) : null;
// ...
}
On your service class use the fetch way that is set on flutter documentation to simplify your code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<UserModel>> fetchUsers(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/users');
return parseUsers(response.body);
}
List<UserModel> parseUsers(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<UserModel>((json) => UserModel.fromJson(json)).toList();
}
and once you get the data from json you can access to every object based on the hierarchy inside the json, in your case the stateful widget would look like, where i replace the name and the phone with latitude inside the geo and city inside the address
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
fetchUsers(http.Client()).then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text(user.name),
subtitle: Text(user.address.geo.lat),
trailing: Text(user.address.city),
),
],
);
},
),
),
);
}
}
I hope this help
You can copy paste run full code below
You can directly assign attribute
code snippet
title: Text('${user.name} ${user.address.city} ${user.address.geo.lat}'),
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
List<UserModel> userModelFromJson(String str) =>
List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
UserModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({
this.street,
this.suite,
this.city,
this.zipcode,
this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
String lat;
String lng;
Geo({
this.lat,
this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
String name;
String catchPhrase;
String bs;
Company({
this.name,
this.catchPhrase,
this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeView(title: 'Flutter Demo Home Page'),
);
}
}
class Services {
static const String url = 'https://jsonplaceholder.typicode.com/users';
static Future<List<UserModel>> getUsers() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
final List<UserModel> users = userModelFromJson(response.body);
return users;
} else {
return List<UserModel>();
}
} catch (e) {
return List<UserModel>();
}
}
}
class HomeView extends StatefulWidget {
HomeView({Key key, this.title}) : super(key: key);
final String title;
#override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text('${user.name} ${user.address.city} ${user.address.geo.lat}'),
subtitle: Text(user.email),
trailing: Text(user.phone),
),
],
);
},
),
),
);
}
}

How to Parse Nested JSON

I'm able to parse the JSON using following code,
Map<String, dynamic> map = jsonDecode(response.body); // import 'dart:convert';
List<dynamic> datalist = map['data'];
I got List dynamic but i need data list
My problem is if I get product items in data list then how should i parse the JSON. I got stuck here.
When it comes to nested array of JSON, how to parse it.
**
{
"status": 0,
"message": "Product Not Found",
"data": [{
"id": "1",
"product_name": "Pet 0.5",
"qty": "500",
"unit": "ml",
"product_img": "SRC.jpg",
"description": "sgsdgdfhdfhh",
"sale_price": "100",
"donation_amt": "10"
},
{
"id": "7",
"product_name": "Pet 1l",
"qty": "1",
"unit": "l",
"product_img": "SRC1.jpg",
"description": "dgdg",
"sale_price": "20",
"donation_amt": "1"
}
]
}
**
My dart code for the JSON
class ProductList {
int status;
String message;
List<Data> data;
ProductList({this.status, this.message, this.data});
ProductList.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String id;
String productName;
String qty;
String unit;
String productImg;
String description;
String salePrice;
String donationAmt;
Data(
{this.id,
this.productName,
this.qty,
this.unit,
this.productImg,
this.description,
this.salePrice,
this.donationAmt});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
productName = json['product_name'];
qty = json['qty'];
unit = json['unit'];
productImg = json['product_img'];
description = json['description'];
salePrice = json['sale_price'];
donationAmt = json['donation_amt'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['product_name'] = this.productName;
data['qty'] = this.qty;
data['unit'] = this.unit;
data['product_img'] = this.productImg;
data['description'] = this.description;
data['sale_price'] = this.salePrice;
data['donation_amt'] = this.donationAmt;
return data;
}
}
This is the code below for the drop down list. We need to populate the drop down with the product name and id. The product name and id fields are there in the data part of the JSON
Padding(
padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
child: Container(
width: 160,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton<Product>(
value: selectedUser,
icon: Padding(
padding: const EdgeInsets.only(left:15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (Product newValue) {
setState(() {
selectedUser = newValue;
});
},
items: users.map((Product user) {
return DropdownMenuItem<Product>(
value: user,
child: Padding(
padding:
const EdgeInsets.only(left: 10.0),
child: Text(
user.name,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
So as you Described i have made some changes and loaded you json locally, you can make a api call and then everything is the same:
{
"status": 0,
"message": "Product Not Found",
"data": [
{
"id": "1",
"product_name": "Pet 0.5",
"qty": "500",
"unit": "ml",
"product_img": "SRC.jpg",
"description": "sgsdgdfhdfhh",
"sale_price": "100",
"donation_amt": "10"
},
{
"id": "7",
"product_name": "Pet 1l",
"qty": "1",
"unit": "l",
"product_img": "SRC1.jpg",
"description": "dgdg",
"sale_price": "20",
"donation_amt": "1"
}
]
}
json you provided
// To parse this JSON data, do
//
// final productList = productListFromJson(jsonString);
import 'dart:convert';
ProductList productListFromJson(String str) =>
ProductList.fromJson(json.decode(str));
String productListToJson(ProductList data) => json.encode(data.toJson());
class ProductList {
int status;
String message;
List<Datum> data;
ProductList({
this.status,
this.message,
this.data,
});
factory ProductList.fromJson(Map<String, dynamic> json) => ProductList(
status: json["status"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String id;
String productName;
String qty;
String unit;
String productImg;
String description;
String salePrice;
String donationAmt;
Datum({
this.id,
this.productName,
this.qty,
this.unit,
this.productImg,
this.description,
this.salePrice,
this.donationAmt,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
productName: json["product_name"],
qty: json["qty"],
unit: json["unit"],
productImg: json["product_img"],
description: json["description"],
salePrice: json["sale_price"],
donationAmt: json["donation_amt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"product_name": productName,
"qty": qty,
"unit": unit,
"product_img": productImg,
"description": description,
"sale_price": salePrice,
"donation_amt": donationAmt,
};
}
creating the model class for the json
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_testing_project/models.dart';
main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _currentSelectedValue;
List<Datum> data = List();
bool _isLoading = false;
String selectedUser;
#override
void initState() {
// TODO: implement initState
super.initState();
loadYourData();
}
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
loadYourData() async {
setState(() {
_isLoading = true;
});
// Loading your json locally you can make an api call, when you get the response just pass it to the productListFromJson method
String jsonString = await loadFromAssets();
final productList = productListFromJson(jsonString);
data = productList.data;
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _isLoading
? Text('Loading')
: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
child: Container(
width: 160,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton(
value: selectedUser,
isExpanded: true,
icon: Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (newValue) {
setState(() {
selectedUser = newValue;
});
},
hint: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Select'),
),
items: data.map((data) {
return DropdownMenuItem(
value: data.id,
child: Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Text(
data.id + ':' + data.productName,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
),
),
);
}
}
check out the changes that i have made using your same ui.
Let me know if its working.
Thanks.
Remember: "JSON is not 'nested.'" When you're given a JSON string, you decode it and this gives you a data-structure ... which very well might be "nested." How to handle that correctly is up to you.
Always treat JSON (or YAML, or XML) as a "black box." Use the utilities provided in the language to encode, decode and parse them.

Flutter/Dart Error - NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments

I'm receiving an Error following the Json Deserialisation cookbook
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
Bundle Class
class Bundle {
String resourceType;
String id;
String type;
int total;
List<Link> link;
List<Entry> entry;
Bundle(
{this.resourceType,
this.id,
this.type,
this.total,
this.link,
this.entry});
factory Bundle.fromJson(Map<String, dynamic> json) {
return Bundle(
resourceType : json['resourceType'],
id : json['id'],
type : json['type'],
total : json['total'],
);
}
Code:
try {
await parsePerson(resultString);
} catch (e) {
print('Bundlelist Error: $e');
}
Future<List<Bundle>> parsePerson(String body) async {
List<Bundle> bundleList = [];
try {
final parsed = json.decode(body);
bundleList = parsed.map<Bundle>((json) => Bundle.fromJson(json)).toList;
} catch (e) {
print('FutureError: $e');
}
return bundleList;
}
My Result string (partial): Full json is here.
{"resourceType":"Bundle","id":"f26779b4-5c3c-4c52-83b4-c689516a6a08","type":"searchset","link":[{"relation":"self","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?name=b\u0026_count=20"},{"relation":"next","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?-pageContext=7018d2bc-6be4-48e1-b8a4-a40f4e98c98c\u0026-pageDirection=NEXT"}],"entry":[{"fullUrl":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient/6160015","resource":{"resourceType":"Patient","id":"6160015","meta":{"versionId":"0","lastUpdated":"2019-07-08T20:37:03.000Z"},"text":{"status":"generated","div":"\u003Cdiv\u003E\u003Cp\u003E\u003Cb\u003EPatient\u003C/b\u003E\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EName\u003C/b\u003E: 111d3fcaffb244b2b207c07ffa5a14, bf607a7f1f284e8aa3559d52249bc7\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EDOB\u003C/b\u003E: Mar 15, 1936\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EAdministrative Gend
I've tried various suggestions from here including:
final parsed = jsonDecode(body).cast<Map<String, dynamic>>();
Returns
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
I'm quite lost as to what to try next.
You need an array, but your response is a map
You json string is too long, I can not paste full code contains your full json
You can copy paste , replace yourjsonstring and run full code below
Your json string contains control character \n and need to replace before parse
You can get all related class in full code
code snippet
String jsonString = '''yourjsonstring''';
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String resourceType;
String id;
String type;
List<Link> link;
List<Entry> entry;
Payload({
this.resourceType,
this.id,
this.type,
this.link,
this.entry,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
resourceType: json["resourceType"],
id: json["id"],
type: json["type"],
link: List<Link>.from(json["link"].map((x) => Link.fromJson(x))),
entry: List<Entry>.from(json["entry"].map((x) => Entry.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceType,
"id": id,
"type": type,
"link": List<dynamic>.from(link.map((x) => x.toJson())),
"entry": List<dynamic>.from(entry.map((x) => x.toJson())),
};
}
class Entry {
String fullUrl;
Resource resource;
Entry({
this.fullUrl,
this.resource,
});
factory Entry.fromJson(Map<String, dynamic> json) => Entry(
fullUrl: json["fullUrl"],
resource: Resource.fromJson(json["resource"]),
);
Map<String, dynamic> toJson() => {
"fullUrl": fullUrl,
"resource": resource.toJson(),
};
}
class Resource {
ResourceType resourceType;
String id;
Meta meta;
TextClass text;
List<Identifier> identifier;
bool active;
List<Name> name;
List<Telecom> telecom;
Gender gender;
DateTime birthDate;
List<Address> address;
Resource({
this.resourceType,
this.id,
this.meta,
this.text,
this.identifier,
this.active,
this.name,
this.telecom,
this.gender,
this.birthDate,
this.address,
});
factory Resource.fromJson(Map<String, dynamic> json) => Resource(
resourceType: resourceTypeValues.map[json["resourceType"]],
id: json["id"],
meta: Meta.fromJson(json["meta"]),
text: TextClass.fromJson(json["text"]),
identifier: List<Identifier>.from(json["identifier"].map((x) => Identifier.fromJson(x))),
active: json["active"],
name: List<Name>.from(json["name"].map((x) => Name.fromJson(x))),
telecom: List<Telecom>.from(json["telecom"].map((x) => Telecom.fromJson(x))),
gender: genderValues.map[json["gender"]],
birthDate: DateTime.parse(json["birthDate"]),
address: List<Address>.from(json["address"].map((x) => Address.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceTypeValues.reverse[resourceType],
"id": id,
"meta": meta.toJson(),
"text": text.toJson(),
"identifier": List<dynamic>.from(identifier.map((x) => x.toJson())),
"active": active,
"name": List<dynamic>.from(name.map((x) => x.toJson())),
"telecom": List<dynamic>.from(telecom.map((x) => x.toJson())),
"gender": genderValues.reverse[gender],
"birthDate": "${birthDate.year.toString().padLeft(4, '0')}-${birthDate.month.toString().padLeft(2, '0')}-${birthDate.day.toString().padLeft(2, '0')}",
"address": List<dynamic>.from(address.map((x) => x.toJson())),
};
}
class Address {
AddressUse use;
String text;
List<String> line;
String city;
String state;
String postalCode;
String country;
AddressPeriod period;
Address({
this.use,
this.text,
this.line,
this.city,
this.state,
this.postalCode,
this.country,
this.period,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
use: addressUseValues.map[json["use"]],
text: json["text"],
line: List<String>.from(json["line"].map((x) => x)),
city: json["city"],
state: json["state"],
postalCode: json["postalCode"],
country: json["country"],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": addressUseValues.reverse[use],
"text": text,
"line": List<dynamic>.from(line.map((x) => x)),
"city": city,
"state": state,
"postalCode": postalCode,
"country": country,
"period": period == null ? null : period.toJson(),
};
}
class AddressPeriod {
DateTime start;
AddressPeriod({
this.start,
});
factory AddressPeriod.fromJson(Map<String, dynamic> json) => AddressPeriod(
start: DateTime.parse(json["start"]),
);
Map<String, dynamic> toJson() => {
"start": start.toIso8601String(),
};
}
enum AddressUse { HOME, WORK, MOBILE }
final addressUseValues = EnumValues({
"home": AddressUse.HOME,
"mobile": AddressUse.MOBILE,
"work": AddressUse.WORK
});
enum Gender { UNKNOWN, OTHER }
final genderValues = EnumValues({
"other": Gender.OTHER,
"unknown": Gender.UNKNOWN
});
class Identifier {
IdentifierUse use;
Type type;
IdentifierSystem system;
String identifierValue;
Value value;
AddressPeriod period;
Identifier({
this.use,
this.type,
this.system,
this.identifierValue,
this.value,
this.period,
});
factory Identifier.fromJson(Map<String, dynamic> json) => Identifier(
use: identifierUseValues.map[json["use"]],
type: Type.fromJson(json["type"]),
system: identifierSystemValues.map[json["system"]],
identifierValue: json["value"],
value: Value.fromJson(json["_value"]),
period: AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": identifierUseValues.reverse[use],
"type": type.toJson(),
"system": identifierSystemValues.reverse[system],
"value": identifierValue,
"_value": value.toJson(),
"period": period.toJson(),
};
}
enum IdentifierSystem { URN_OID_2168401113883378700, URN_OID_111111, URN_OID_21684011138833421000110000112 }
final identifierSystemValues = EnumValues({
"urn:oid:1.1.1.1.1.1": IdentifierSystem.URN_OID_111111,
"urn:oid:2.16.840.1.113883.3.42.10001.100001.12": IdentifierSystem.URN_OID_21684011138833421000110000112,
"urn:oid:2.16.840.1.113883.3.787.0.0": IdentifierSystem.URN_OID_2168401113883378700
});
class Type {
List<Coding> coding;
TextEnum text;
Type({
this.coding,
this.text,
});
factory Type.fromJson(Map<String, dynamic> json) => Type(
coding: json["coding"] == null ? null : List<Coding>.from(json["coding"].map((x) => Coding.fromJson(x))),
text: textEnumValues.map[json["text"]],
);
Map<String, dynamic> toJson() => {
"coding": coding == null ? null : List<dynamic>.from(coding.map((x) => x.toJson())),
"text": textEnumValues.reverse[text],
};
}
class Coding {
String system;
Code code;
Display display;
bool userSelected;
Coding({
this.system,
this.code,
this.display,
this.userSelected,
});
factory Coding.fromJson(Map<String, dynamic> json) => Coding(
system: json["system"],
code: codeValues.map[json["code"]],
display: displayValues.map[json["display"]],
userSelected: json["userSelected"],
);
Map<String, dynamic> toJson() => {
"system": system,
"code": codeValues.reverse[code],
"display": displayValues.reverse[display],
"userSelected": userSelected,
};
}
enum Code { MR }
final codeValues = EnumValues({
"MR": Code.MR
});
enum Display { MEDICAL_RECORD_NUMBER }
final displayValues = EnumValues({
"Medical record number": Display.MEDICAL_RECORD_NUMBER
});
enum TextEnum { COMMUNITY_MEDICAL_RECORD_NUMBER, MRN, MILITARY_ID }
final textEnumValues = EnumValues({
"Community Medical Record Number": TextEnum.COMMUNITY_MEDICAL_RECORD_NUMBER,
"Military Id": TextEnum.MILITARY_ID,
"MRN": TextEnum.MRN
});
enum IdentifierUse { USUAL }
final identifierUseValues = EnumValues({
"usual": IdentifierUse.USUAL
});
class Value {
List<Extension> extension;
Value({
this.extension,
});
factory Value.fromJson(Map<String, dynamic> json) => Value(
extension: List<Extension>.from(json["extension"].map((x) => Extension.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"extension": List<dynamic>.from(extension.map((x) => x.toJson())),
};
}
class Extension {
String url;
String valueString;
Extension({
this.url,
this.valueString,
});
factory Extension.fromJson(Map<String, dynamic> json) => Extension(
url: json["url"],
valueString: json["valueString"],
);
Map<String, dynamic> toJson() => {
"url": url,
"valueString": valueString,
};
}
class Meta {
String versionId;
DateTime lastUpdated;
Meta({
this.versionId,
this.lastUpdated,
});
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
versionId: json["versionId"],
lastUpdated: DateTime.parse(json["lastUpdated"]),
);
Map<String, dynamic> toJson() => {
"versionId": versionId,
"lastUpdated": lastUpdated.toIso8601String(),
};
}
class Name {
NameUse use;
String text;
List<String> family;
List<String> given;
List<String> prefix;
NamePeriod period;
List<String> suffix;
Name({
this.use,
this.text,
this.family,
this.given,
this.prefix,
this.period,
this.suffix,
});
factory Name.fromJson(Map<String, dynamic> json) => Name(
use: nameUseValues.map[json["use"]],
text: json["text"],
family: List<String>.from(json["family"].map((x) => x)),
given: List<String>.from(json["given"].map((x) => x)),
prefix: json["prefix"] == null ? null : List<String>.from(json["prefix"].map((x) => x)),
period: json["period"] == null ? null : NamePeriod.fromJson(json["period"]),
suffix: json["suffix"] == null ? null : List<String>.from(json["suffix"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"use": nameUseValues.reverse[use],
"text": text,
"family": List<dynamic>.from(family.map((x) => x)),
"given": List<dynamic>.from(given.map((x) => x)),
"prefix": prefix == null ? null : List<dynamic>.from(prefix.map((x) => x)),
"period": period == null ? null : period.toJson(),
"suffix": suffix == null ? null : List<dynamic>.from(suffix.map((x) => x)),
};
}
class NamePeriod {
DateTime start;
DateTime end;
NamePeriod({
this.start,
this.end,
});
factory NamePeriod.fromJson(Map<String, dynamic> json) => NamePeriod(
start: json["start"] == null ? null : DateTime.parse(json["start"]),
end: json["end"] == null ? null : DateTime.parse(json["end"]),
);
Map<String, dynamic> toJson() => {
"start": start == null ? null : start.toIso8601String(),
"end": end == null ? null : end.toIso8601String(),
};
}
enum NameUse { OFFICIAL, OLD }
final nameUseValues = EnumValues({
"official": NameUse.OFFICIAL,
"old": NameUse.OLD
});
enum ResourceType { PATIENT }
final resourceTypeValues = EnumValues({
"Patient": ResourceType.PATIENT
});
class Telecom {
TelecomSystem system;
ValueEnum value;
AddressUse use;
AddressPeriod period;
Telecom({
this.system,
this.value,
this.use,
this.period,
});
factory Telecom.fromJson(Map<String, dynamic> json) => Telecom(
system: telecomSystemValues.map[json["system"]],
value: valueEnumValues.map[json["value"]],
use: addressUseValues.map[json["use"]],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"system": telecomSystemValues.reverse[system],
"value": valueEnumValues.reverse[value],
"use": addressUseValues.reverse[use],
"period": period == null ? null : period.toJson(),
};
}
enum TelecomSystem { PHONE, EMAIL }
final telecomSystemValues = EnumValues({
"email": TelecomSystem.EMAIL,
"phone": TelecomSystem.PHONE
});
enum ValueEnum { THE_3213213213, NAME_FAKEMAIL_COM, THE_8888888888 }
final valueEnumValues = EnumValues({
"name#fakemail.com": ValueEnum.NAME_FAKEMAIL_COM,
"321-321-3213": ValueEnum.THE_3213213213,
"888-888-8888": ValueEnum.THE_8888888888
});
class TextClass {
Status status;
String div;
TextClass({
this.status,
this.div,
});
factory TextClass.fromJson(Map<String, dynamic> json) => TextClass(
status: statusValues.map[json["status"]],
div: json["div"],
);
Map<String, dynamic> toJson() => {
"status": statusValues.reverse[status],
"div": div,
};
}
enum Status { GENERATED }
final statusValues = EnumValues({
"generated": Status.GENERATED
});
class Link {
String relation;
String url;
Link({
this.relation,
this.url,
});
factory Link.fromJson(Map<String, dynamic> json) => Link(
relation: json["relation"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"relation": relation,
"url": url,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''yourjsonstring''';
//String jsonString = '''{"newLine": "here is a \n newline \u003E \u0026 \u003C aaa"}''';
void _incrementCounter() {
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}