Why can't i get data value from json - flutter - json

Am trying to get values from my json file categories.json using flutter but am always getting error or its not showing and I don't really know what is wrong
This is my main.dart
Future<List<Category>> loadData() async {
String jString = await rootBundle.loadString("assets/categories.json");
List<dynamic> jRes = jsonDecode(jString);
List<Category> datas = jRes.map((e) => Category.fromJson(e)).toList();
return datas;
}
Container(
child: FutureBuilder<List<Category>>(
future: loadData(),
builder: (context, data) {
if (data.connectionState != ConnectionState.waiting &&
data.hasData) {
var userList = data.data;
return ListView.builder(
itemCount: userList.length,
itemBuilder: (context, index) {
var userData = userList[index];
return Column(
children: [
Text("Category: ${userData.catName}"),
],
);
});
} else {
return Center(
child: CircularProgressIndicator(),
);
}
})),
and my model.dart
class Category {
String catId;
String catName;
SubCategory subcat;
Category({this.catId, this.catName, this.subcat});
factory Category.fromJson(Map<String, dynamic> json) {
return Category(
catId: json['cat_id'],
catName: json['category'],
subcat: SubCategory.fromJson(json['cat_subcategory']),
);
}
Map<String, dynamic> toJson() {
return {
"cat_id": catId,
"category": catName,
};
}
}
class SubCategory {
String subName, subImage;
SubCategory({this.subName, this.subImage});
factory SubCategory.fromJson(Map<String, dynamic> json) {
return SubCategory(subName: json['sub_name'], subImage: json['sub_image']);
}
Map<String, dynamic> toJson() {
return {
"sub_name": subName,
"sub_image": subImage,
};
}
}
and lastly my categories.json file
[{
"category": "Design & Creativity",
"cat_id": "1",
"cat_subcategory": [
{
"sub_name": "Ads",
"sub_image": "https://images.unsplash.com/photo-1589838017489-9198a27bd040?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8YWR2ZXJ0aXNlbWVudHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
}
]
}]
//There are more of them
The problem am facing when I run it is that it only shows me the CircularProgressIndicator() in my main.dart and when I remove the if statement, it says Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null. Please how do I go about solving this problem and if you need more explanation then tell me
PS: When I check the loadData() value it says type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
EDIT: Thank you all for the answers but what i did was to generate a model using this website model generator
and i was able to get the value

Personally, when I want to load data from json file, I do this:
Future<List<Category>> loadData() async {
List<Category> datas = [];
return rootBundle.loadString("assets/categories.json").then((value) {
List<dynamic> jRes = jsonDecode(value);
jRes.forEach((element) {
datas.add(Category.fromJson(element));
});
return datas;
});
}
Also, in SubCategory class
factory SubCategory.fromJson(Map<String, dynamic> json) {
return SubCategory(subName: json['sub_name'], subImage: json['sub_image']);
}
Your fromJson() require Map<String, dynamic>.
But if you look at your file
"cat_subcategory": [
{
"sub_name": "Ads",
"sub_image": "https://images.unsplash.com/photo-1589838017489-9198a27bd040?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8YWR2ZXJ0aXNlbWVudHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
}
]
You can see that cat_subcategory is a List
So you are giving a List to your SubCategory.fromJson() instead of a Map.
If you want to give a Map, you can simply give the first index of your list
Your Category.fromJson() become
factory Category.fromJson(Map<String, dynamic> json) {
return Category(
catId: json['cat_id'],
catName: json['category'],
subcat: SubCategory.fromJson(json['cat_subcategory'][0]),
);
}

Change your model.dart class
class Category {
String category;
String catId;
List<CatSubcategory> catSubcategory;
Category({this.category, this.catId, this.catSubcategory});
Category.fromJson(Map<String, dynamic> json) {
category = json['category'];
catId = json['cat_id'];
if (json['cat_subcategory'] != null) {
catSubcategory = new List<CatSubcategory>();
json['cat_subcategory'].forEach((v) {
catSubcategory.add(new CatSubcategory.fromJson(v));
});
}}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['category'] = this.category;
data['cat_id'] = this.catId;
if (this.catSubcategory != null) {
data['cat_subcategory'] =
this.catSubcategory.map((v) => v.toJson()).toList();
}
return data;
}}
class CatSubcategory {
String subName;
String subImage;
CatSubcategory({this.subName, this.subImage});
CatSubcategory.fromJson(Map<String, dynamic> json) {
subName = json['sub_name'];
subImage = json['sub_image'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sub_name'] = this.subName;
data['sub_image'] = this.subImage;
return data;
}}
And Replace
List<Category> datas = jRes.map((e) => Category.fromJson(e)).toList();
with
List<Category> datas = List<Category>.from(jRes.map((category)=> Category.fromJson(category)));

Related

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'SubJsonModel' - flutter

Am trying to get a data from a json url but i get the error
Unhandled Exception: type 'List' is not a subtype of type 'SubJsonModel'
main.dart
final String url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
#override
void initState() {
// TODO: implement initState
super.initState();
loadData();
}
loadData() async {
var res = await http.get(url, headers: {"Accept":"application/json"});
if(res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for(var data in jsonDecode) {
myModel.add(JsonModel(data['cat_id'], data['category'], data['cat_subcategory']));
setState(() {});
}
print(myModel[1].subCat.name);
}else {
print("Something went wrong!");
}
}
model.dart
class JsonModel {
final String id;
final String category;
SubJsonModel subCat;
JsonModel(this.id, this.category, this.subCat);
}
class SubJsonModel {
final String name;
final String image;
SubJsonModel(this.name, this.image);
}
please how do i solve this
So here what I do first create a model class with the help of this online tool. And then changed code like first save subcategory in one list and then passed it to the main list and then print
Here is my loadData() method
final String url =
'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List myModel = [];
loadData() async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for (var data in jsonDecode) {
List<CatSubcategory> subCate = []; // Set a emoty list of CatSubcategory
data['cat_subcategory'].map((x) { // Here parsed the cat_subcategory data and simply add it into list
return subCate.add(
CatSubcategory(subName: x['sub_name'], subImage: x['sub_image']));
}).toList(); // and this done for we get map data so convert this data toList();
myModel.add(JsonModel(
category: data['category'],
catId: data['cat_id'],
catIcon: data['cat_icon'],
catSubcategory: subCate));
setState(() {});
}
print(myModel[0].catSubcategory[0].subName);
} else {
print("Something went wrong!");
}
}
here is my model class
class JsonModel {
JsonModel({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(
json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon,
"cat_subcategory":
List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
You can use https://app.quicktype.io/ to create the model.dart from a json.
To parse this JSON data, do
final pieSingleChartInfo = pieSingleChartInfoFromJson(jsonString);
import 'dart:convert';
List<PieSingleChartInfo> pieSingleChartInfoFromJson(String str) => List<PieSingleChartInfo>.from(json.decode(str).map((x) => PieSingleChartInfo.fromJson(x)));
String pieSingleChartInfoToJson(List<PieSingleChartInfo> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class PieSingleChartInfo {
PieSingleChartInfo({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory PieSingleChartInfo.fromJson(Map<String, dynamic> json) => PieSingleChartInfo(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"] == null ? null : json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon == null ? null : catIcon,
"cat_subcategory": List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
I noted a few issues and corrected them based on the information you provided.
Read the comments. Add a sample response body to the question.
final String url =
'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
#override
void initState() {
// TODO: implement initState
super.initState();
loadData();
}
loadData() async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for (var data in jsonDecode) {
// first create SubJsonModel object
var subCat = SubJsonModel(
data['cat_subcategory']['name'], data['cat_subcategory']['image']);
//use subCat to create JsonModel
myModel.add(JsonModel(data['cat_id'], data['category'], subCat));
setState(() {});
}
print(myModel[1].subCat.name);
} else {
print("Something went wrong!");
}
}

Not getting required value from json list - flutter

I have this code where am able to get values from an online json data and print its value
main.dart
final String url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
List<CatSubcategory> subCate = [];
int localInt;
#override
void initState() {
// TODO: implement initState
super.initState();
localInt = 0;
loadData(localInt);
}
loadData(int dataInt) async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for (var data in jsonDecode) {
data['cat_subcategory'].map((x) {
return subCate.add(
CatSubcategory(subName: x['sub_name'], subImage: x['sub_image']));
}).toList();
myModel.add(JsonModel(
category: data['category'],
catId: data['cat_id'],
catIcon: data['cat_icon'],
catSubcategory: subCate));
setState(() {});
}
print(myModel[dataInt].catSubcategory.length);
} else {
print("Something went wrong!");
}
}
my model.dart
class JsonModel {
JsonModel({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(
json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon,
"cat_subcategory":
List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
The only problem am having now is that when I try to print the length on the subcategory of the first list it gives me 24 instead of 6 and i printed it like this myModel[dataInt].catSubcategory.length. The dataInt is 0 which means it's supposed to print out the length of the children("cat_subcategory") with category of Design & Creativity but it's printing all the other children of the other lis. So please how do i go about this. And if you need more explanation tell me
I would avoid writing your own model from scratch if you already know the schema of your json.
Just use something like https://app.quicktype.io/ just paste your json and you will get
import 'dart:convert';
class Root {
Root({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory Root.fromJson(Map<String, dynamic> json) => Root(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"] == null ? null : json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon == null ? null : catIcon,
"cat_subcategory": List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
and then you should be good to just
loadData(int dataInt) async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var list = json.decode(resBody) as List;
List<Root> items = list.map((i)=>Root.fromJson(i)).toList();
print(items[0].catSubcategory.length);
}
} else {
print("Something went wrong!");
}
}
https://repl.it/talk/share/Sample/118111

Parsing JSON Object with unique key in Dart

I'm having a hard time figuring out how to parse a JSON response that has unique keys into nested object.
I've done some research and came across this article (https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51) but it doesn't give an example of a JSON object with unique/random keys.
See below for the json response I get from the backend. The student usernames are unique (i.e. john354, kim553, etc) and a new student could get added at any time. Could someone give me an example of what my model should look like for this type of structure and how to display the data with listview.builder? Thank you so much!
{
"school": {
"students": {
"john354": {
"fullName": "John Kindle",
"permissions": {
"permission1": "here",
"permission2": "here"
}
},
"kim553": {
"fullName": "Kim Johnson"
"permissions": {
"permission1": "here",
"permission2": "here"
}
},
"dory643": {
"fullName": "Dory Thomas"
"permissions": {
"permission1": "here",
"permission2": "here"
}
}
},
"footer": "Text goes here"
},
"status": {
"state": "open"
}
}
Attempt Data Model
class School {
School school;
Status status;
School({this.school, this.status});
School.fromJson(Map<String, dynamic> json) {
school =
json['school'] != null ? new School.fromJson(json['school']) : null;
status =
json['status'] != null ? new Status.fromJson(json['status']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.school != null) {
data['school'] = this.school.toJson();
}
if (this.status != null) {
data['status'] = this.status.toJson();
}
return data;
}
}
class School {
Students students;
String footer;
School({this.students, this.footer});
School.fromJson(Map<String, dynamic> json) {
students = json['students'] != null
? new Students.fromJson(json['students'])
: null;
footer = json['footer'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.students != null) {
data['students'] = this.students.toJson();
}
data['footer'] = this.footer;
return data;
}
}
class Students {
final String username;
final Info info;
Options({this.username,this.info});
factory Students.fromJson(String name, Map<String, dynamic> json){
return Students(
username: username,
info: Info(
fullName: json['info']['fullName']
)
);
}
}
class Info {
String fullName;
Permissions permissions;
Info({this.fullName, this.permissions});
Info.fromJson(Map<String, dynamic> json) {
fullName = json['fullName'];
permissions = json['permissions'] != null
? new Permissions.fromJson(json['permissions'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['fullName'] = this.fullName;
if (this.permissions != null) {
data['permissions'] = this.permissions.toJson();
}
return data;
}
}
class Permissions {
String permission1;
String permission2;
Permissions({this.permission1, this.permission2});
Permissions.fromJson(Map<String, dynamic> json) {
permission1 = json['permission1'];
permission2 = json['permission2'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['permission1'] = this.permission1;
data['permission2'] = this.permission2;
return data;
}
}
class Status {
String state;
Status({this.state});
Status.fromJson(Map<String, dynamic> json) {
state = json['state'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['state'] = this.state;
return data;
}
}
To simplify JSON pursing you can use app.quicktype.io to convert JSON to DART.
try the Following Data Model,
import 'dart:convert';
School schoolFromJson(String str) => School.fromJson(json.decode(str));
String schoolToJson(School data) => json.encode(data.toJson());
class School {
School({
this.school,
this.status,
});
final SchoolClass school;
final Status status;
factory School.fromJson(Map<String, dynamic> json) => School(
school: SchoolClass.fromJson(json["school"]),
status: Status.fromJson(json["status"]),
);
Map<String, dynamic> toJson() => {
"school": school.toJson(),
"status": status.toJson(),
};
}
class SchoolClass {
SchoolClass({
this.students,
this.footer,
});
final Map<String, Student> students;
final String footer;
factory SchoolClass.fromJson(Map<String, dynamic> json) => SchoolClass(
students: Map.from(json["students"]).map((k, v) => MapEntry<String, Student>(k, Student.fromJson(v))),
footer: json["footer"],
);
Map<String, dynamic> toJson() => {
"students": Map.from(students).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
"footer": footer,
};
}
class Student {
Student({
this.fullName,
this.permissions,
});
final String fullName;
final Permissions permissions;
factory Student.fromJson(Map<String, dynamic> json) => Student(
fullName: json["fullName"],
permissions: Permissions.fromJson(json["permissions"]),
);
Map<String, dynamic> toJson() => {
"fullName": fullName,
"permissions": permissions.toJson(),
};
}
class Permissions {
Permissions({
this.permission1,
this.permission2,
});
final String permission1;
final String permission2;
factory Permissions.fromJson(Map<String, dynamic> json) => Permissions(
permission1: json["permission1"],
permission2: json["permission2"],
);
Map<String, dynamic> toJson() => {
"permission1": permission1,
"permission2": permission2,
};
}
class Status {
Status({
this.state,
});
final String state;
factory Status.fromJson(Map<String, dynamic> json) => Status(
state: json["state"],
);
Map<String, dynamic> toJson() => {
"state": state,
};
}
To parse this JSON data, do
final school = schoolFromJson(jsonString);

Why is my json code gives Instance of Post

I am trying to fetch data from internet. And this is the json string:
{"channel":{"id":1090161,"name":"İscaklik","description":"İscakliği okeyrum da.","latitude":"0.0","longitude":"0.0","field1":"nem","field2":"iscaklik","created_at":"2020-06-27T11:56:47Z","updated_at":"2020-06-27T11:56:47Z","last_entry_id":1},"feeds":[{"created_at":"2020-06-27T12:02:32Z","entry_id":1,"field1":"5"}]}
I want to get the "field1" in "feeds".
And my code is like that:
class _DataState extends State<Data> {
Future<String> AlbumState;
void initState() {
super.initState();
oku();
}
var a;
Future<List<Post>> oku() async {
final response = await http.get(
'https://api.thingspeak.com/channels/1090161/fields/1.json?api_key=JD9JYHAT2YHOI5Q3&results=1');
if (response.statusCode == 200) {
var responseJson = json.decode(response.body);
return (responseJson['feeds'] as List)
.map((p) => Post.fromJson(p))
.toList();
} else {
throw Exception('La bulamadık la böyle bi şey yoh la');
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: FutureBuilder<List<Post>>(
future: oku(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.toString());
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
),
),
);
}
}
class Post {
final String field1;
Post({this.field1});
factory Post.fromJson(Map<String, dynamic> json) {
return new Post(
field1: json['entry_id'].toString(),
);
}
}
This is the result:
I want to see the 5.(Which is the field1 of feeds)
Why I am seeing this?
How can I fix this?
Because you trying to use the entire object like the String in the Text widget. Try to call the attribute field1 you have in the Post class.
return Text(snapshot.data[0].field1);
Just Copy And Paste this model class and the simple use
if (response.statusCode == 200) {
var responseJson = json.decode(response.body);
ModelChannel channel = ModelChannel.fromJson(responseJson);
return channel.feeds;
} else {
throw Exception('La bulamadık la böyle bi şey yoh la');
}
Here is your JSON model
class ModelChannel {
Channel channel;
List<Feed> feeds;
ModelChannel({this.channel, this.feeds});
factory ModelChannel.fromJson(Map<String, dynamic> json) {
return ModelChannel(
channel: json['channel'] != null ? Channel.fromJson(json['channel']) : null,
feeds: json['feeds'] != null ? (json['feeds'] as List).map((i) => Feed.fromJson(i)).toList() : null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.channel != null) {
data['channel'] = this.channel.toJson();
}
if (this.feeds != null) {
data['feeds'] = this.feeds.map((v) => v.toJson()).toList();
}
return data;
}
}
class Feed {
String created_at;
int entry_id;
String field1;
Feed({this.created_at, this.entry_id, this.field1});
factory Feed.fromJson(Map<String, dynamic> json) {
return Feed(
created_at: json['created_at'],
entry_id: json['entry_id'],
field1: json['field1'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['created_at'] = this.created_at;
data['entry_id'] = this.entry_id;
data['field1'] = this.field1;
return data;
}
}
class Channel {
String created_at;
String description;
String field1;
String field2;
int id;
int last_entry_id;
String latitude;
String longitude;
String name;
String updated_at;
Channel({this.created_at, this.description, this.field1, this.field2, this.id, this.last_entry_id, this.latitude, this.longitude, this.name, this.updated_at});
factory Channel.fromJson(Map<String, dynamic> json) {
return Channel(
created_at: json['created_at'],
description: json['description'],
field1: json['field1'],
field2: json['field2'],
id: json['id'],
last_entry_id: json['last_entry_id'],
latitude: json['latitude'],
longitude: json['longitude'],
name: json['name'],
updated_at: json['updated_at'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['created_at'] = this.created_at;
data['description'] = this.description;
data['field1'] = this.field1;
data['field2'] = this.field2;
data['id'] = this.id;
data['last_entry_id'] = this.last_entry_id;
data['latitude'] = this.latitude;
data['longitude'] = this.longitude;
data['name'] = this.name;
data['updated_at'] = this.updated_at;
return data;
}
}
You may refer to this code, You should call the attribute data.feeds[0].field1-
function ItemListCtrl($scope, $http) {
$http.get("https://api.thingspeak.com/channels/1090161/fields/1.json?api_key=JD9JYHAT2YHOI5Q3&results=1", {
headers: {
'Content-Type': 'application/json'
}
}).success(function(data) {
console.log(data.feeds[0].field1)
$scope.data = angular.fromJson(data.feeds[0].field1);
});
}
Fiddle

Flutter how to get the data of a json

Good I have the following problem I have a json the following http:// and I have the class to get the data for which use https://app.quicktype.io/ and the code is as follows
// To parse this JSON data, do
//
// final moviesFirstLoad = moviesFirstLoadFromJson(jsonString);
import 'dart:convert';
MoviesFirstLoad moviesFirstLoadFromJson(String str) {
final jsonData = json.decode(str);
return MoviesFirstLoad.fromJson(jsonData);
}
String moviesFirstLoadToJson(MoviesFirstLoad data) {
final dyn = data.toJson();
return json.encode(dyn);
}
class MoviesFirstLoad {
List<Movierecent> movierecent;
MoviesFirstLoad({
this.movierecent,
});
factory MoviesFirstLoad.fromJson(Map<String, dynamic> json) => new MoviesFirstLoad(
movierecent: new List<Movierecent>.from(json["movierecent"].map((x) => Movierecent.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"movierecent": new List<dynamic>.from(movierecent.map((x) => x.toJson())),
};
}
class Movierecent {
int id;
String movieId;
String title;
String genre;
String myear;
String released;
String runtime;
String rated;
String director;
String actors;
String plot;
String imdbrating;
String type;
String production;
int internalid;
String poster;
Movierecent({
this.id,
this.movieId,
this.title,
this.genre,
this.myear,
this.released,
this.runtime,
this.rated,
this.director,
this.actors,
this.plot,
this.imdbrating,
this.type,
this.production,
this.internalid,
this.poster,
});
factory Movierecent.fromJson(Map<String, dynamic> json) => new Movierecent(
id: json["id"],
movieId: json["movieID"],
title: json["title"],
genre: json["genre"],
myear: json["myear"],
released: json["released"],
runtime: json["runtime"],
rated: json["rated"],
director: json["director"],
actors: json["actors"],
plot: json["plot"],
imdbrating: json["imdbrating"],
type: json["type"],
production: json["production"],
internalid: json["internalid"],
poster: json["poster"],
);
Map<String, dynamic> toJson() => {
"id": id,
"movieID": movieId,
"title": title,
"genre": genre,
"myear": myear,
"released": released,
"runtime": runtime,
"rated": rated,
"director": director,
"actors": actors,
"plot": plot,
"imdbrating": imdbrating,
"type": type,
"production": production,
"internalid": internalid,
"poster": poster,
};
}
Now the first label shows me that I should use
final moviesFirstLoad = moviesFirstLoadFromJson(jsonString);
therefore I have the following and here I do not know what to do as accessing the data to place them in a list would be something like
Future<List<Movierecent>> loadMovies() async {
final response = await http.get("http://emovies.evolucionone.com/");
if (response.statusCode == 200){
final moviesFirstLoad = moviesFirstLoadFromJson(response.body);
return moviesFirstLoad.movierecent;
}else{
throw Exception ('Failed to load Data');
}
}
I need help to get the data of the json if someone helps me I have already read several topics but none of them works for me ...
Well I answer my questions myself
This to get the data from json
Future<MoviesFirstLoad> loadMovies() async {
final Response response = await http.get(dogApiUrl);
//final List<Movierecent> posterimage = List<Movierecent>();
if (response.statusCode == 200){
//final responsejson = json.decode(response.body);
final moviesFirstLoad = moviesFirstLoadFromJson(response.body);
// moviesFirstLoad.movierecent.forEach((poster) => posterimage.add(poster));
print(moviesFirstLoad);
return moviesFirstLoad;
}else{
throw Exception ('Failed to load Data');
}
}
to show the data in a list
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Movies')),
body: FutureBuilder(
future: loadMovies(),
builder: (BuildContext context, AsyncSnapshot<AppData> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data.movierecent.length,
itemBuilder: (BuildContext context, int index) {
final Movierecent movie = snapshot.data.movierecent[index];
return ListTile(
title: Text(movie.title),
subtitle: Text(movie.genre),
);
},
);
},
),
);
}
}
loadMovies() returns Future<List<Movierecent>> which is a future. If you want underlying list of movies, you could do someting like
loadMovies().then((List<Movierecent> movieList) {
/* do what you want to do here like invoking setState()....*/
}.catchError((e) {
/* Handle Error scenario here */
};
You might want to refer Dart documentation of Futures