Flutter: Join specific field of JSON file together to become a list itself - json

I have a json file with a list of different types of data.
I wanted to join the "name" field of all attractions of each city together as a list.
The expected result after joining, for example for Longo city will be like this:
Attraction1
Attraction2
The data in JSON file is structured like this:
{
"city": "London",
"attractions": [
{
"name": "Attraction1",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction2",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Hong Kong",
"attractions": [
{
"name": "Attraction3",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction4",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Cario",
"attractions": [
{
"name": "Attraction5",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction6",
"localrank": 4,
"intrank": 5
}
]
}
]
I used the following code, but I get an error :
cities.attractions.name.join("\n")
Json model class is this:
List<Cities> citiesFromJson(String str) =>
List<Cities>.from(json.decode(str).map((x) => Cities.fromJson(x)));
String citiesToJson(List<Cities> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Cities {
Cities({
this.city,
this.attractions,
});
String city;
List<Attraction> attractions;
factory Cities.fromRawJson(String str) => Cities.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Cities.fromJson(Map<String, dynamic> json) => Cities(
city: json["city"],
attractions: List<Attraction>.from(
json["attractions"].map((x) => Attraction.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"city": city,
"attractions": List<dynamic>.from(attractions.map((x) => x.toJson())),
};
}
class Attraction {
Attraction({
this.name,
this.localrank,
this.intrank,
});
String name;
int localrank;
int intrank;
factory Attraction.fromRawJson(String str) =>
Attraction.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Attraction.fromJson(Map<String, dynamic> json) => Attraction(
name: json["name"],
localrank: json["localrank"],
intrank: json["intrank"],
);
Map<String, dynamic> toJson() => {
"name": name,
"localrank": localrank,
"intrank": intrank,
};
}
And this also calling json file:
Future<String> fetchData() async {
String data =
await DefaultAssetBundle.of(context).loadString("assets/data.json");
final jsonResult = json.decode(data);
print('$jsonResult oop');
this.setState(() {
jsonResult.forEach(
(element) => Globals.citylist.add(new Cities.fromJson(element)));
});
return "Success!";
}

Something like that should work:
import 'dart:convert';
var data = """ [{
"city": "London",
"attractions": [
{
"name": "Attraction1",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction2",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Hong Kong",
"attractions": [
{
"name": "Attraction3",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction4",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Cario",
"attractions": [
{
"name": "Attraction5",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction6",
"localrank": 4,
"intrank": 5
}
]
}
] """;
List<Cities> citiesFromJson(String str) =>
List<Cities>.from(json.decode(str).map((x) => Cities.fromJson(x)));
String citiesToJson(List<Cities> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Cities {
Cities({
this.city,
this.attractions,
});
String city;
List<Attraction> attractions;
factory Cities.fromRawJson(String str) => Cities.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Cities.fromJson(Map<String, dynamic> json) => Cities(
city: json["city"],
attractions: List<Attraction>.from(
json["attractions"].map((x) => Attraction.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"city": city,
"attractions": List<dynamic>.from(attractions.map((x) => x.toJson())),
};
}
class Attraction {
Attraction({
this.name,
this.localrank,
this.intrank,
});
String name;
int localrank;
int intrank;
factory Attraction.fromRawJson(String str) =>
Attraction.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Attraction.fromJson(Map<String, dynamic> json) => Attraction(
name: json["name"],
localrank: json["localrank"],
intrank: json["intrank"],
);
Map<String, dynamic> toJson() => {
"name": name,
"localrank": localrank,
"intrank": intrank,
};
}
class Globals {
static List<Cities> citylist = [];
}
Future<String> fetchData() async {
// String data =
// await DefaultAssetBundle.of(context).loadString("assets/data.json");
final jsonResult = json.decode(data);
print('$jsonResult oop');
// this.setState(() {
jsonResult.forEach(
(element) => Globals.citylist.add(new Cities.fromJson(element)));
// });
var result = getAttractionsByCity('London');
print(result.join('\n'));
return "Success!";
}
List<String> getAttractionsByCity(String value) {
var result = <String>[];
for (final city in Globals.citylist) {
if (city.city == value) {
final attractions = city.attractions;
for (final attraction in attractions) {
result.add(attraction.name);
}
}
}
return result;
}
void main() async {
await fetchData();
}
It's a working example. You can copy and paste this code to HTTP://dartpad.dev and run it to see the result.

Related

How to fetch a data from JSON in flutter?

I have a JSON file and i want to fetch the data.
here a small Json example, in this Example as we see the employee has 2 properties,
name and List of countries :
{
"Employee": [
{
"id":1
"name": "John",
"Countries": [
{
"id" :1
"country": "Uk"
},
{
"id" :2
"country": "USA"
},
{
"id" :3
"country": "Germany"
}
]
}
]
}
I used to use this method to fetch the data from JSON but the problem i faced is that this method works just with Json that doesnt have a list property :
Future<List<EmployeeModel>> fetchEmployeeList() async {
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var data = jsonDecode(response.body) as List;
print(data);
final employeeList = data.map((e) => EmployeeModel.fromJson(e)).toList();
return employeeList;
} else {
throw Exception("Failed to load ");
}
} catch (e) {
print(e);
rethrow;
}
}
here the model file :
import 'dart:convert';
List<EmployeeModel> employeeModelFromJson(String str) =>
List<EmployeeModel>.from(
json.decode(str).map((x) => EmployeeModel.fromJson(x)));
String employeeModelToJson(List<EmployeeModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class EmployeeModel {
EmployeeModel({
this.id,
this.name,
this.countries,
});
int id;
String name;
List<Country> countries;
factory EmployeeModel.fromJson(Map<String, dynamic> json) => EmployeeModel(
id: json["id"],
name: json["name"],
countries: List<Country>.from(
json["Countries"].map((x) => Country.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"Countries": List<dynamic>.from(countries.map((x) => x.toJson())),
};
}
class Country {
Country({
this.id,
this.country,
});
int id;
String country;
factory Country.fromJson(Map<String, dynamic> json) => Country(
id: json["id"],
country: json["country"],
);
Map<String, dynamic> toJson() => {
"id": id,
"country": country,
};
}
var data = jsonDecode(response.body);
print(data['Employee'][0]['Countries'][0]['country'];
//Output uk
Also consider creating a model for the json so you can parse it easily and don't have to write named keys.
https://docs.flutter.dev/development/data-and-backend/json
There are some online tools like quicktype.io too
EDIT
final employeeList = data.map((e) => EmployeeModel.fromJson(e)).toList();
print(employeeList[0].countries [0].country);
//Output uk

Put JSON Data in Flutter Stacked Chart

I have try to put my JSON data in flutter Stacked Chart.
I already work on simple charts using JSON Data like bar, column, pie, Doughnut charts etc.
I have refer
stacked-column-chart(syncfusion_flutter_charts),
Grouped Bar Chart(charts_flutter)
Stack Overflow Que-Ans
below like my API response/JSON String
[{
"name": "ABC",
"subject": [{
"name": "Math",
"marks": "54"
},
{
"name": "Physics",
"marks": "65"
}
]
},
{
"name": "PQR",
"subject": [{
"name": "Chemistry",
"marks": "53"
},
{
"name": "Biology",
"marks": "22"
},
{
"name": "English",
"marks": "7 "
},
{
"name": "Math",
"marks": "12"
}
]
}, {
"name": "JKL",
"subject": [{
"name": "Chemistry",
"marks": "53"
},
{
"name": "Biology",
"marks": "22"
},
{
"name": "English",
"marks": "79 "
},
{
"name": "Math",
"marks": "12"
},
{
"name": "Physics",
"marks": "72"
}
]
}
]
Or I want below type of graph using JSON Data
Note: Suggest me my JSON string is wrong, you can create your own JSON data and display the output
Using charts_flutter. Please customize it for your usecase its a bare minimum implementation to validate that its working for your json.
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'dart:convert';
class StackedBarChart extends StatelessWidget {
final bool animate;
StackedBarChart({this.animate = false});
// EXCLUDE_FROM_GALLERY_DOCS_END
#override
Widget build(BuildContext context) {
String jsonString = '[{"name":"ABC","subject":[{"name":"Math","marks":"54"},{"name":"Physics","marks":"65"}]},{"name":"PQR","subject":[{"name":"Chemistry","marks":"53"},{"name":"Biology","marks":"22"},{"name":"English","marks":"7 "},{"name":"Math","marks":"12"}]},{"name":"JKL","subject":[{"name":"Chemistry","marks":"53"},{"name":"Biology","marks":"22"},{"name":"English","marks":"79 "},{"name":"Math","marks":"12"},{"name":"Physics","marks":"72"}]}]';
final studentMarks = studentMarksFromJson(jsonString);
var subjects = <Subject?>{};
var subjectsDist = <Subject?>{};
int c=0;
for (var stdnt in studentMarks) {
for (var subjs in stdnt.subject) {
if (!subjectsDist.where((element) => element?.name==subjs.name).isNotEmpty) {
subjs.sno=c++;
subjectsDist.add(subjs);
}
}
}
print(subjectsDist.length);
List<List<OrdinalMarks>> SubjectData = [];
for (var subjs in subjectsDist) {
List<OrdinalMarks> marksData = [];
for (var stdnt in studentMarks) {
if (stdnt.subject
.where((element) => element.name == subjs?.name).isNotEmpty) {
var temp = stdnt.subject
.where((element) => element.name == subjs?.name)
.first;
marksData.add(OrdinalMarks(temp.name, int.parse(temp.marks),stdnt.name));
} else {
marksData.add(OrdinalMarks(subjs!.name, 0,stdnt.name));
}
}
SubjectData.add(marksData);
}
var palettes = charts.MaterialPalette.getOrderedPalettes(subjectsDist.length+2);
int cnt=0;
List<charts.Series<OrdinalMarks, String>> chartData = [
];
for(var d in SubjectData)
{
chartData.add(new charts.Series<OrdinalMarks, String>(
id: d.first.subjectName,
domainFn: (OrdinalMarks m, _) => m.studentName,
measureFn: (OrdinalMarks m, _) => m.marks,
data: d,
fillColorFn: ( subj, _) {
// print(subj.subjectName+": subj.subjectName :" + pallets[subj.subjectName].toString()??charts.MaterialPalette.blue.shadeDefault.toString());
return palettes.elementAt( subjectsDist.where((element) => element?.name==subj.subjectName).first?.sno??0 ).shadeDefault; //pallets[subj.subjectName]??charts.MaterialPalette.blue.shadeDefault;
},
colorFn: ( subj, _) {
// print(subj.subjectName+": subj.subjectName :" + pallets[subj.subjectName].toString()??charts.MaterialPalette.blue.shadeDefault.toString());
return palettes.elementAt(subjectsDist.where((element) => element?.name==subj.subjectName).first?.sno??0).shadeDefault;
},
));
}
return Scaffold(
// Use Obx(()=> to update Text() whenever count is changed.
appBar: AppBar(title: Text("Chart")),
// Replace the 8 lines Navigator.push by a simple Get.to(). You don't need context
body:new charts.BarChart(
chartData,
animate: animate,
behaviors: [new charts.SeriesLegend(showMeasures: true)],
animationDuration: Duration(seconds: 3),
));
}
}
/// Sample ordinal data type.
class OrdinalMarks {
final String subjectName;
final int marks;
final String studentName;
OrdinalMarks(this.subjectName, this.marks,this.studentName);
}
List<StudentMarks> studentMarksFromJson(String str) => List<StudentMarks>.from(json.decode(str).map((x) => StudentMarks.fromJson(x)));
String studentMarksToJson(List<StudentMarks> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class StudentMarks {
StudentMarks({
required this.name,
required this.subject,
});
String name;
List<Subject> subject;
factory StudentMarks.fromJson(Map<String, dynamic> json) => StudentMarks(
name: json["name"],
subject: List<Subject>.from(json["subject"].map((x) => Subject.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"subject": List<dynamic>.from(subject.map((x) => x.toJson())),
};
}
class Subject {
Subject({
required this.name,
required this.marks,
});
String name;
String marks;
int? sno;
factory Subject.fromJson(Map<String, dynamic> json) => Subject(
name: json["name"],
marks: json["marks"],
);
Map<String, dynamic> toJson() => {
"name": name,
"marks": marks,
};
}

Store Deserialized json in a list of objects Flutter

I have successfully deserialized my json file. I have stored one element of the json in one object successfully , but i am getting a problem storing the objects in a list.
I tried every possible solution from the internet below you will see the trials i have made.
This is my code
class _MyHomePageState extends State<MyHomePage> {
String? _chosenSubCounty;
List<County> counties = [];
Future<String> getJson() async {
final jsonResult = await rootBundle.loadString('assets/json_files/counties.json');
List<dynamic> parsedListJson = jsonDecode(jsonResult);
print(parsedListJson[0]);//prints {name: Baringo, capital: Kabarnet, code: 30, sub_counties: [Baringo central, Baringo north, Baringo south, Eldama ravine, Mogotio, Tiaty]}
final county = County.fromJson(parsedListJson[0]);
print(county.name.toString());//prints Baringo
//trial no 1 failed
counties = parsedListJson.map((i)=>County.fromJson(i)).toList();
//trial no 2 also failed
counties = List<County>.from(parsedListJson.map((i) => County.fromJson(i)));
//trial no 3 also failed
for(int i = 0; i < parsedListJson.length; i++){
counties.add(County.fromJson(parsedListJson[i]));
}
print(counties);//prints Error: Expected a value of type 'String', but got one of type 'Null'
return jsonResult;
}
#override
void initState() {
getJson();
}
#override
Widget build(BuildContext context) {..........}
}
This is Model Class
import 'dart:convert';
List<County> countyFromJson(String str) => List<County>.from(json.decode(str).map((x) => County.fromJson(x)));
String countyToJson(List<County> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class County {
String name;
String capital;
int code;
List subCounties;
County({
required this.name,
required this.capital,
required this.code,
required this.subCounties,
});
factory County.fromJson(Map<String, dynamic> json) {
return County(
name: json["name"],
capital: json["capital"],
code: json["code"],
subCounties: List<String>.from(json["sub_counties"])
);
}
Map<String, dynamic> toJson() => {
"name": name,
"capital": capital == null ? null : capital,
"code": code,
"sub_counties": List<dynamic>.from(subCounties.map((x) => x)),
};
}
This is the json file
[
{
"name": "Baringo",
"capital": "Kabarnet",
"code": 30,
"sub_counties": [
"Baringo central",
"Baringo north",
"Baringo south",
"Eldama ravine",
"Mogotio",
"Tiaty"
]
},
{
"name": "Bomet",
"capital": "Bomet",
"code": 36,
"sub_counties": [
"Bomet central",
"Bomet east",
"Chepalungu",
"Konoin",
"Sotik"
]
},
]
First remove comma after your 2nd json Object from your json file. Then use this code to parse your json. I've run the project and it works totally fine.
import 'package:flutter/material.dart';
import 'package:stacksolution/county_model.dart';
class FetchData extends StatefulWidget {
const FetchData({Key? key}) : super(key: key);
#override
_FetchDataState createState() => _FetchDataState();
}
class _FetchDataState extends State<FetchData> {
#override
void initState() {
// TODO: implement initState
callJson();
super.initState();
}
callJson() async {
String jsonString =
await DefaultAssetBundle.of(context).loadString('assets/county.json');
List<CountyModel> list = countyFromJson(jsonString);
print("$list");
}
#override
Widget build(BuildContext context) {
return Container();
}
}
The Model class:
import 'dart:convert';
List<CountyModel> countyFromJson(String str) => List<CountyModel>.from(
json.decode(str).map((x) => CountyModel.fromJson(x)));
String countyToJson(List<CountyModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountyModel {
CountyModel({
this.name,
this.capital,
this.code,
this.subCounties,
});
String? name;
String? capital;
int? code;
List<String>? subCounties;
factory CountyModel.fromJson(Map<String, dynamic> json) => CountyModel(
name: json["name"],
capital: json["capital"],
code: json["code"],
subCounties: List<String>.from(json["sub_counties"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"name": name,
"capital": capital,
"code": code,
"sub_counties": List<dynamic>.from(subCounties!.map((x) => x)),
};
}
The Json File:
[
{
"name": "Baringo",
"capital": "Kabarnet",
"code": 30,
"sub_counties": [
"Baringo central",
"Baringo north",
"Baringo south",
"Eldama ravine",
"Mogotio",
"Tiaty"
]
},
{
"name": "Bomet",
"capital": "Bomet",
"code": 36,
"sub_counties": [
"Bomet central",
"Bomet east",
"Chepalungu",
"Konoin",
"Sotik"
]
}
]

Flutter Rest Api Connection - How to get data?

I am a beginner in Flutter. I was trying to extract data from api. I got response like this
"status": "success",
"data": {
"integration": "051st93cqk90gqeyuikkkii1s5il5d3p",
"rootcategory": 2,
"slider": [
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787d5beb55.png",
"type": "category",
"id": "6",
"sort_order": "0.00"
},
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787fb306c7.png",
"type": "product",
"id": "5",
"sort_order": "1.00"
}
],
"noimg": "https://omanphone.smsoman.com/api/media/omanphone_icon.png",
"catimages": [
{
"id": "6",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b4857e526dd.jpg"
},
{
"id": "7",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d4142c0b.jpeg"
},
{
"id": "8",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d6440439.jpeg"
},
{
"id": "11",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d7c6974c.jpeg"
}
],
"store_id": 1,
"minimum_order_amount": null,
"stores": [
],
"currency": "OMR",
"payment_imgs": [
"https://omanphone.smsoman.com/api/media/payment_all.png",
"https://omanphone.smsoman.com/api/media/cards.png"
],
"voucher_cat": 151,
"whatsapp": "96812345678",
"celebrity_id": 0,
"register_otp": "0",
"mobile_formats": [
{
"webiste": "base",
"len": 8,
"country_code": "+968",
"country": "OM",
"id": 1
}
],
"cmspages": {
"faq": 73,
"about": 72,
"terms": 71,
"privacy": 70
},
"pay_method_imgs": [
"https://omanphone.smsoman.com/pub/media/itoons/payment-icon.png",
"https://omanphone.smsoman.com/pub/media/itoons/cod-icon.png"
]
}
}
Using app.quicktype.io - I converted this data to model.
like below.
// To parse this JSON data, do
//
// final slideData = slideDataFromJson(jsonString);
import 'dart:convert';
SlideData slideDataFromJson(String str) => SlideData.fromJson(json.decode(str));
String slideDataToJson(SlideData data) => json.encode(data.toJson());
class SlideData {
SlideData({
this.status,
this.data,
});
String status;
Data data;
factory SlideData.fromJson(Map<String, dynamic> json) => SlideData(
status: json["status"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": data.toJson(),
};
}
class Data {
Data({
this.integration,
this.rootcategory,
this.slider,
this.noimg,
this.catimages,
this.storeId,
this.minimumOrderAmount,
this.stores,
this.currency,
this.paymentImgs,
this.voucherCat,
this.whatsapp,
this.celebrityId,
this.registerOtp,
this.mobileFormats,
this.cmspages,
this.payMethodImgs,
});
String integration;
int rootcategory;
List<Slider> slider;
String noimg;
List<Catimage> catimages;
int storeId;
dynamic minimumOrderAmount;
List<dynamic> stores;
String currency;
List<String> paymentImgs;
int voucherCat;
String whatsapp;
int celebrityId;
String registerOtp;
List<MobileFormat> mobileFormats;
Cmspages cmspages;
List<String> payMethodImgs;
factory Data.fromJson(Map<String, dynamic> json) => Data(
integration: json["integration"],
rootcategory: json["rootcategory"],
slider: List<Slider>.from(json["slider"].map((x) => Slider.fromJson(x))),
noimg: json["noimg"],
catimages: List<Catimage>.from(json["catimages"].map((x) => Catimage.fromJson(x))),
storeId: json["store_id"],
minimumOrderAmount: json["minimum_order_amount"],
stores: List<dynamic>.from(json["stores"].map((x) => x)),
currency: json["currency"],
paymentImgs: List<String>.from(json["payment_imgs"].map((x) => x)),
voucherCat: json["voucher_cat"],
whatsapp: json["whatsapp"],
celebrityId: json["celebrity_id"],
registerOtp: json["register_otp"],
mobileFormats: List<MobileFormat>.from(json["mobile_formats"].map((x) => MobileFormat.fromJson(x))),
cmspages: Cmspages.fromJson(json["cmspages"]),
payMethodImgs: List<String>.from(json["pay_method_imgs"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"integration": integration,
"rootcategory": rootcategory,
"slider": List<dynamic>.from(slider.map((x) => x.toJson())),
"noimg": noimg,
"catimages": List<dynamic>.from(catimages.map((x) => x.toJson())),
"store_id": storeId,
"minimum_order_amount": minimumOrderAmount,
"stores": List<dynamic>.from(stores.map((x) => x)),
"currency": currency,
"payment_imgs": List<dynamic>.from(paymentImgs.map((x) => x)),
"voucher_cat": voucherCat,
"whatsapp": whatsapp,
"celebrity_id": celebrityId,
"register_otp": registerOtp,
"mobile_formats": List<dynamic>.from(mobileFormats.map((x) => x.toJson())),
"cmspages": cmspages.toJson(),
"pay_method_imgs": List<dynamic>.from(payMethodImgs.map((x) => x)),
};
}
class Catimage {
Catimage({
this.id,
this.img,
});
String id;
String img;
factory Catimage.fromJson(Map<String, dynamic> json) => Catimage(
id: json["id"],
img: json["img"],
);
Map<String, dynamic> toJson() => {
"id": id,
"img": img,
};
}
class Cmspages {
Cmspages({
this.faq,
this.about,
this.terms,
this.privacy,
});
int faq;
int about;
int terms;
int privacy;
factory Cmspages.fromJson(Map<String, dynamic> json) => Cmspages(
faq: json["faq"],
about: json["about"],
terms: json["terms"],
privacy: json["privacy"],
);
Map<String, dynamic> toJson() => {
"faq": faq,
"about": about,
"terms": terms,
"privacy": privacy,
};
}
class MobileFormat {
MobileFormat({
this.webiste,
this.len,
this.countryCode,
this.country,
this.id,
});
String webiste;
int len;
String countryCode;
String country;
int id;
factory MobileFormat.fromJson(Map<String, dynamic> json) => MobileFormat(
webiste: json["webiste"],
len: json["len"],
countryCode: json["country_code"],
country: json["country"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"webiste": webiste,
"len": len,
"country_code": countryCode,
"country": country,
"id": id,
};
}
class Slider {
Slider({
this.image,
this.type,
this.id,
this.sortOrder,
});
String image;
String type;
String id;
String sortOrder;
factory Slider.fromJson(Map<String, dynamic> json) => Slider(
image: json["image"],
type: json["type"],
id: json["id"],
sortOrder: json["sort_order"],
);
Map<String, dynamic> toJson() => {
"image": image,
"type": type,
"id": id,
"sort_order": sortOrder,
};
}
Future<void> getDataFromInternet() async {
//getting data from Internet
try {
var response =
await http.get('https://omanphone.smsoman.com/api/configuration');
} catch (error) {
print(error);
}
}
I just want to get slider images. So What did I need to do in above code?
I used http package and var response =
await http.get('https://omanphone.smsoman.com/api/configuration'); did this. But I don't know how to extract it.

Not able to parse json data in flutter

I am not able to parse below mentioned json data in flutter.
[
{
"id": 96,
"name": "Entertainment",
"link": "https://thehappilyeverafter.in/listing-category/entertainment/",
"image": "https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg",
"children": [
{
"child_id": 114,
"child_name": "DJs",
"child_link": "https://thehappilyeverafter.in/listing-category/djs/"
},
{
"child_id": 117,
"child_name": "Live Music",
"child_link": "https://thehappilyeverafter.in/listing-category/live-music/"
},
{
"child_id": 115,
"child_name": "Wedding Choreographer",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-choreographer/"
},
{
"child_id": 116,
"child_name": "Wedding Entertainment",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-entertainment/"
}
]
}
]`
import 'dart:convert';
List<Root> rootFromJson(String str) => List<Root>.from(json.decode(str).map((x) => Root.fromJson(x)));
String rootToJson(List<Root> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Root {
Root({
this.id,
this.name,
this.link,
this.image,
this.children,
});
int id;
String name;
String link;
String image;
List<Children> children;
factory Root.fromJson(Map<String, dynamic> json) => Root(
id: json["id"],
name: json["name"],
link: json["link"],
image: json["image"] == null ? null : json["image"],
children: List<Children>.from(json["children"].map((x) => Children.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"link": link,
"image": image == null ? null : image,
"children": List<dynamic>.from(children.map((x) => x.toJson())),
};
}
class Children {
Children({
this.childId,
this.childName,
this.childLink,
});
int childId;
String childName;
String childLink;
factory Children.fromJson(Map<String, dynamic> json) => Children(
childId: json["child_id"],
childName: json["child_name"],
childLink: json["child_link"],
);
Map<String, dynamic> toJson() => {
"child_id": childId,
"child_name": childName,
"child_link": childLink,
};
}
[Getting this error][1]
`
type 'List' is not a subtype of type 'Children'
Since your json is a list, you should loop through it:
final List<Root> roots = yourJson.map((element) {
return Root.fromJson(element);
}).toList();
print(roots.first.image);
//https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg