Data got from my api looks like this and I need to get the elements all inside "5f1916a05bc6cb3f055c20bc" without doing jsonResponse["5f1916a05bc6cb3f055c20bc"]["video"] because the value of "5f1916a05bc6cb3f055c20bc" changes per item. Are there any ways that I can create a model for this?
{
"5f1916a05bc6cb3f055c20bc": "{
"video": "",
"image": "",
"likes": 0,
"dislikes": 0,
"trash": 0,
"createdAt": "2020-07-23T04: 48: 00.000Z",
"id": "5f1916a05bc6cb3f055c20bc",
"author": "5eeb7edbac4dba7b6d3e68c1",
"userTag": "#doeee",
"text": "Checking again",
"campus": "University Of Technology",
"__v": 0
}
}
Just check out this code and let me know if it works:
This will dynamically get the key value pairs:
import 'dart:convert';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
getData();
}
getData() async {
String data =
await DefaultAssetBundle.of(context).loadString("json/parse.json");
var jsonData = json.decode(data);
jsonData.forEach((key, value) {
if (key != "socketID") {
print('This is key : $key');
print('This is the value : $value');
// Following are the specific object value:
value.forEach((key, value) {
print('$key');
print('$value');
});
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(body: Text(''));
}
}
Let me know if it works.
const object1={
"socketID": "H7Cddg9o6rbyvB_TAAAC",
"5f1916a05bc6cb3f055c20bc":{
"video": "",
"image": "",
"likes": 0,
"dislikes": 0,
"trash": 0,
"createdAt": "2020-07-23T04: 48: 00.000Z",
"id": "5f1916a05bc6cb3f055c20bc",
"author": "5eeb7edbac4dba7b6d3e68c1",
"userTag": "#doeee",
"text": "Checking again",
"campus": "University Of Technology",
"__v": 0.
}
}
Var Z=Object.keys(object1);
You can print them in console to check the result
Console.log(Z);
Now this Z will hold your array of Keys in your response,then you can use For loop to get specific key value based on their Index
var Response =await http.get("Your API URL",headers: {"Accept": "application/json"},);
if (Response.statusCode == 200)
{
var data = json.decode(Response.body);
var result=Object.keys(data);
console.log(Object.keys(result));// Array ["socketID", "5f1916a05bc6cb3f055c20bc"]
console.log(result[1]); //"5f1916a05bc6cb3f055c20bc"
}
Now your required key is in result[1],just use this and parse data
Related
I am an absolute beginner and would appreciate your help very much.
My json is as follows:
[
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.humidity",
"val": 73,
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.temperature",
"val": 16.8,
"ts": 1661671736782,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherCondition",
"val": "CLEAR",
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherDayTime",
"val": "DAY",
"ts": 1661671736783,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windDirection",
"val": 10,
"ts": 1661671736784,
"ack": true
},
{
"id": "hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windSpeed",
"val": 18.503999999999998,
"ts": 1661671736784,
"ack": true
}
]
When I want to pick and show a particular value, e.g. for humidity, I get the following error:
type 'String' is not a subtype of 'int' of 'index'
My dart-code is as follows:
class EinzelwerteList {
final List<Wetter> einzelwerte;
EinzelwerteList({
required this.einzelwerte,
});
factory EinzelwerteList.fromJson(List<dynamic> parsedJson) {
List<Wetter> einzelwerte = <Wetter>[];
einzelwerte = parsedJson.map((i) => Wetter.fromJson(i)).toList();
return new EinzelwerteList(einzelwerte: einzelwerte);
}
}
class Wetter {
final String id;
final Int val;
final Int ts;
final Bool ack;
Wetter({
required this.id,
required this.val,
required this.ts,
required this.ack,
});
factory Wetter.fromJson(Map<String, dynamic> json) {
return Wetter(
id: json['id'].toString(),
val: json['val'],
ts: json['ts'],
ack: json['ack']);
}
}
Future<Wetter> fetchWetter() async {
final response = await http.get(Uri.parse(
'http://192.168.178.37:8087/getBulk/hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.humidity,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.temperature,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherCondition,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.weatherDayTime,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windDirection,hmip.0.homes.18c6789e-30e6-46c3-ba4b-1f94d284c178.weather.windSpeed'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var dataDecoded = jsonDecode(response.body);
var humidity = dataDecoded['einzelwerte'][0]['val'].toString();
debugPrint(humidity);
return Wetter.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Wetter');
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Wetter> futureWetter;
#override
void initState() {
super.initState();
futureWetter = fetchWetter();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.green,
//scaffoldBackgroundColor:
),
home: Scaffold(
appBar: AppBar(
title: const Text('Micha lernt Flutter & Dart'),
),
body: Center(
child: FutureBuilder<Wetter>(
future: futureWetter,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.val.toString());
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Container();
},
),
),
),
);
}
}
What do I do wrong?
As I said I am a total newbie and try to learn. So please be patient even if I ask dumb question.
Best regards.
There are multiple problems but the specific problem you are getting right now is the following piece of code:
var dataDecoded = jsonDecode(response.body);
var humidity = dataDecoded['einzelwerte'][0]['val'].toString();
The JSON does not contain a Map as the first level but instead a List. So you are getting an error since a List expects an int inside the [] while you are providing a String.
Another problem, you are going to have later, is that you are using the wrong types in your Wetter class. The types Int and Bool comes from dart:ffi and is meant to be used if you are integrating with native C code.
You should instead use int and bool.
A third problem is that val in your JSON contains a mix of types. So in your example you can see it is sometimes double and other times int and sometime String... the mix of int and double can be solved by use the num type but you need to add some custom handling for the String.
I'm trying to integrate the api using class model. here is my api response look like.
{
"status": 1,
"message": "your rides",
"data": [
{
"id": 2,
"ride_user_id": "4",
"ride_driver_id": "2",
"pick_up": "gsdhjhsgdf",
"drop_of": "dsfbsdjbf",
"date": null,
"time": "10.55",
"status": "complete",
"created_at": "2022-06-17T09:50:25.000000Z",
"updated_at": "2022-06-17T09:56:37.000000Z",
"driver": {
"id": 2,
"name": "driver",
"vehicle_number": null,
"licence_number": null,
"state": null,
"image": null,
"notification": 1,
"created_at": "2022-06-08T16:15:12.000000Z",
"updated_at": "2022-06-08T16:15:44.000000Z"
},
"rideperson": {
"id": 4,
"name": "ab",
"vehicle_number": null,
"licence_number": null,
"state": "ascascas",
"image": "profile/1735772987889499.jfif",
"notification": 1,
"created_at": "2022-06-09T07:54:41.000000Z",
"updated_at": "2022-06-16T06:48:37.000000Z"
},
"rating": {
"id": 2,
"sender_id": null,
"reciever_id": null,
"ride_id": 2,
"rating": "4",
"created_at": "2022-06-17T09:59:38.000000Z",
"updated_at": "2022-06-17T09:59:38.000000Z"
}
}
]
}
and here is my model
import 'dart:convert';
import 'package:flutter/foundation.dart';
MyRides rideFromJson(String str) => MyRides.fromJson(json.decode(str));
String rideToJson(MyRides data) => json.encode(data.toJson());
class MyRidesDetails {
final int id;
final String pickUp;
final String dropOff;
final String time;
final String rideUserId;
final String rideDriverId;
final List driver;
MyRidesDetails(
{required this.id,
required this.pickUp,
required this.dropOff,
required this.time,
required this.rideUserId,
required this.rideDriverId,
required this.driver
});
factory MyRidesDetails.fromJson(Map<String, dynamic> json) => MyRidesDetails(
id: json['id'],
dropOff: json['drop_of'],
pickUp: json['pick_up'],
time: json['time'],
rideUserId: json['ride_user_id'],
rideDriverId: json['ride_driver_id'],
driver: json['data']['driver']
);
Map<String, dynamic> toJson() => {
'id': id,
'drop_of': dropOff,
'pick_up': pickUp,
'time':time,
'rating':time,
'ride_user_id':rideUserId,
'ride_driver_id':rideDriverId,
'driver':driver
};
}
class MyRides {
MyRides({
required this.status,
required this.message,
required this.data,
});
int status;
String message;
List<MyRidesDetails> data;
factory MyRides.fromJson(Map<String, dynamic> json) => MyRides(
status: json["status"],
message: json["message"],
data: List<MyRidesDetails>.from(json["data"].map((x) => MyRidesDetails.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
here is the code how i'm populating data on my model
Future getAllMyRides(role) async {
Map<String, String> headers = {
"Content-type": "application/json",
'Authorization': 'Bearer $token',
};
var url = Uri.parse(ApiPath.getAllMyRidesUrl+role);
final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
return rideFromJson(response.body).data;
} else {
throw Exception('Failed to load post');
}
}
Now, the question is i want to access this object
"driver": {
"id": 2,
"name": "driver",
"vehicle_number": null,
"licence_number": null,
"state": null,
"image": null,
"notification": 1,
"created_at": "2022-06-08T16:15:12.000000Z",
"updated_at": "2022-06-08T16:15:44.000000Z"
},
using the same model. My model is only accessing the data which is not in object, i want to create a list variable or something on my mode which can access those data which is in object form.
here is the code how i'm calling api function on ui screen
getAllMyRides() async {
setState(() {
_isLoading = true;
});
await Future.delayed(const Duration(seconds: 2), () async {
connectionMsg = await services.checkInternetConnectivity();
if (connectionMsg == "connected") {
try {
var _myRides = await services.getAllMyRides(role);
if (myRides is MyRides) {
print(_myRides.data[0].driver.id); //this should print 2
} else {
print("Unable to fetch data");
}
setState(() {
_isLoading = false;
});
} catch (e) {
print(e);
setState(() {
apiCrashed = true;
});
}
setState(() {
_isLoading = false;
});
} else if (connectionMsg == "not connected") {
AppDialogs().showInfoDialogue(context, "Internet is not working!", () {
Navigator.pop(context);
});
setState(() {
_isLoading = false;
});
}
});
}
#override
void initState() {
super.initState();
getAllMyRides();
}
please help how to do this.Thanks.
var _myRides = await getAllMyRides();
var jsonDecoded = json.decode(_myRides);
print(jsonDecoded['data'][0]['driver']['id']);
please try this
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"
]
}
]
Hi i am building an app and trying to parse nested array of object from an api call back and getting this error
Type String is not the sub Type of Map<String, dynamic>
Here is the model class
class Tournament {
String id;
String title;
String roomID;
String roomPass;
String map;
String type;
String date;
String time;
int joined;
String createdBy;
List<UserIds> joinedUsers;
Tournament(
{this.createdBy,
this.joinedUsers,
this.id,
this.date,
this.map,
this.roomID,
this.roomPass,
this.time,
this.title,
this.type,
this.joined});
factory Tournament.fromJson(Map<String, dynamic> json) {
var list = json['joinedUsers'] as List;
List<UserIds> userList =
list.map((data) => UserIds.fromJson(data)).toList();
return Tournament(
id: json['_id'],
title: json['title'],
roomID: json['roomId'],
roomPass: json['roomPass'],
map: json['mapType'],
type: json['type'],
date: json['date'],
time: json['time'],
joined: json['joined'],
createdBy: json['createdBy'],
joinedUsers: userList);
}
}
class UserIds {
String userId;
UserIds({this.userId});
factory UserIds.fromJson(Map<String, dynamic> parsedJson) {
return UserIds(userId: parsedJson['\$oid']);
}
}
this is the json call back i got
{
"_id": {
"$oid": "5f1c47f2c3c051d9828b1697"
},
"joinedUsers": [{
"$oid": "5f18621d6fca9d3e70a9fabe"
}, {
"$oid": "5f1a7609f7f69d2a1064e5ec"
}],
"title": "HomeComing",
"date": "20-02-2020",
"time": "8:22 Am",
"roomId": "12345",
"roomPass": "12223",
"joined": {
"$numberInt": "9"
},
"mapType": "Erangle",
"type": "Dual",
"createdBy": {
"$oid": "5f16d9bde0fd621dec10e1c5"
},
"__v": {
"$numberInt": "0"
}
}
now when i run this it gave me an error that type String is not the sub type of Map<String, dynamic>
i dont know what wrong i am doing right now
Could you try:
list.map((data) => UserIds.fromJson(JSON.parse(data)).toList();
Could be parse problems, you could log first your elements in your lambda by this to verify what it gives:
list.map((element) =>
{
console.log(data);
//UserIds.fromJson(JSON.parse(data)).toList();
});
Just check out this example that I have made for userIds:
I have taken your json locally.
import 'dart:convert';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}
class UserIds {
String userId;
UserIds({this.userId});
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _isLoading = false;
List<UserIds> userIdsList = List();
#override
void initState() {
super.initState();
getData();
}
getData() async {
String data =
await DefaultAssetBundle.of(context).loadString("json/parse.json");
Map jsonData = json.decode(data);
jsonData['joinedUsers'].forEach((item) {
item.forEach((key, value) {
print('This is the Key $key value $value');
userIdsList.add(UserIds(userId: value));
});
});
print('This is the list ${userIdsList.length}');
}
#override
Widget build(BuildContext context) {
return Scaffold(body: Text(''));
}
}
in the angulardart tutorial, you can't find information on how to get data from a more complex json than in the example
link to the tutorial
json in brauser django rest framework
Content-Type: application/vnd.api+json
Vary: Accept
{
"data": [
{
"type": "Hero",
"id": "1",
"**attributes**": {
"name": "Windstorm"
}
},
{
"type": "Hero",
"id": "2",
"**attributes**": {
"name": "Bombasto"
}
},
{
"type": "Hero",
"id": "3",
"**attributes**": {
"name": "Magneta"
}
},
{
"type": "Hero",
"id": "4",
"**attributes**": {
"name": "Tornado"
}
}
]
}
hero.dart
//if you don't mind, use the tutorial example to show how to output data
class Hero {
final int id;
String name;
Hero(this.id, this.name);
factory Hero.fromJson(Map<String, dynamic> hero) =>
Hero(_toInt(hero['id']), hero['name']);
Map toJson() => {'id': id, 'name': name};
}
int _toInt(id) => id is int ? id : int.parse(id);
hero_service.dart
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'hero.dart';
class HeroService {
static final _headers = {'Content-Type': 'application/json'};
static const _heroesUrl = 'http://127.0.0.1:8000/heroes'; // источник получения данных
final Client _http;
HeroService(this._http);
Future<List<Hero>> getAll() async {
try {
final response = await _http.get(_heroesUrl);
final heroes = (_extractData(response) as List)
.map((value) => Hero.fromJson(value))
.toList();
return heroes;
} catch (e) {
throw _handleError(e);
}
}
Future<Hero> create(String name) async {
try {
final response = await _http.post(_heroesUrl,
headers: _headers, body: json.encode({'name': name}));
return Hero.fromJson(_extractData(response));
} catch (e) {
throw _handleError(e);
}
}
dynamic _extractData(Response resp) => json.decode(resp.body)['data'];
Exception _handleError(dynamic e) {
print(e); // for demo purposes only
return Exception('Server error; cause: $e');
}
}
I don't get errors when working, he just can't get through to the characters...
Your "name" is down a level in the sample json inside of the **attributes** object .. so it would be:
class Hero {
final int id;
String name;
Hero(this.id, this.name);
factory Hero.fromJson(Map<String, dynamic> hero) =>
Hero(_toInt(hero['id']), hero['**attributes**']['name']);
Map toJson() => {'id': id, 'name': name};
}
int _toInt(id) => id is int ? id : int.parse(id);
It's important to not that any level of complexity of JSON can be represented in Dart through parent/child relationships of Map and/or List after being decoded.