Unexpected error while parsing JsonData in flutter - json

Am trying to parse json list data so I could save into an object. But I kept getting errors each time and I do not know why.
Json Data
{
"status": "success",
"data": [
{
"distro_name": "Ikeja Electric (IKEDC)",
"service_id": "ikeja-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Eko Electric (EKEDC)",
"service_id": "eko-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Ibadan Electric (IBEDC)",
"service_id": "ibadan-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Kano Electric (KEDCO)",
"service_id": "kano-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Jos Electricity Distribution (JED)",
"service_id": "jos-electric",
"type": [
"prepaid",
"postpaid"
]
},
{
"distro_name": "Port-Harcourt Electric (PHED)",
"service_id": "portharcourt-electric",
"type": [
"prepaid",
"postpaid"
]
}
]
}
This is my model class for the data.
Model
class Providers {
String distro_name;
String service_id;
dynamic type;
Providers(this.distro_name, this.service_id, this.type);
Providers.fromJson(Map<String, dynamic> json):
distro_name = json['distro_name'],
service_id = json['service_id'],
type = json['type'];
}
Main.dart
fetchProviders() async{
try {
final response = await http.get(
uri,
headers: {'Content-Type': 'application/json','Authorization': 'Bearer ' + _bloc.bearerToken, },
);
final responseJson = json.decode(response.body);
for (var u in responseJson["data"]) {
Providers provider = Providers(
u["distro_name"],
u["service_id"],
u["list"]);
providerList.add(provider);
}
return responseJson;
} catch (exception) {
print(exception);
}
}
This is the error I get.
NoSuchMethodError: The method 'add' was called on null.
I/flutter ( 1366): Receiver: null
I don't really know why I get this error. I don't have null values on my api and I have consumed these kind of json structure in the past.

Initialize providerList:
var providerList = </* type */>[]
for (var u in responseJson["data"]) {
Providers provider = Providers(
u["distro_name"],
u["service_id"],
u["list"]);
providerList.add(provider);
}
Using list map:
providerList = responseJson["data"].map((u) => Providers(
u["distro_name"],
u["service_id"],
u["list"],
)).cast<String>().toList();

Model
class Providers {
String distro_name;
String service_id;
dynamic type;
Providers(this.distro_name, this.service_id, this.type);
Providers.fromJson(Map<String, dynamic> json) => Providers(
json['distro_name'],
json['service_id'],
json['type'],
);
}
Main.dart
fetchProviders() async{
try {
final response = await http.get(
uri,
headers: {'Content-Type': 'application/json','Authorization': 'Bearer ' + _bloc.bearerToken, },
);
final responseJson = json.decode(response.body);
responseJson.forEach((data){
Providers provider = Providers.fromJson(data);
providerList.add(provider);
return responseJson;
});
} catch (exception) {
print(exception);
}
}

model
class Providers {
String distro_name;
String service_id;
dynamic type;
Providers(this.distro_name, this.service_id, this.type);
factory Providers.fromJson(Map<String, dynamic> json){
return Providers(
distro_name = json['distro_name'],
service_id = json['service_id'],
type = json['type'],
);
}
}
main.dart
fetchProviders() async{
try {
final response = await http.get(
uri,
headers: {'Content-Type': 'application/json','Authorization': 'Bearer ' + _bloc.bearerToken, },
);
final responseJson = json.decode(response.body);
for (var u in responseJson['data']) {
Providers provider = Providers.fromJson(u);
providerList.add(provider);
return responseJson;
}
}
catch (exception) {
print(exception);
}
}

Related

How to get the object from array from api response in flutter

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

How to access a JSON array that is inside a JSON object in Dart?

I am a beginner in Flutter and I am trying to build a lyrics app using the API from https://rapidapi.com/brianiswu/api/genius/
The problem is I can't seem to access the array called "hits" that is inside an object called "response"
"response": {
"hits": [
{
"highlights": [],
"index": "song",
"type": "song",
"result": {
"annotation_count": 5,
"api_path": "/songs/6419329",
"artist_names": "ROSÉ",
"full_title": "Gone by ROSÉ",
"header_image_thumbnail_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.300x300x1.jpg",
"header_image_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.1000x1000x1.jpg",
"id": 6419329,
"lyrics_owner_id": 10919416,
"lyrics_state": "complete",
"path": "/Rose-gone-lyrics",
"pyongs_count": 258,
"song_art_image_thumbnail_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.300x300x1.jpg",
"song_art_image_url": "https://images.genius.com/04b543b45bb91449afcf59d62ec55be8.1000x1000x1.jpg",
"stats": {
"unreviewed_annotations": 0,
"concurrents": 6,
"hot": false,
"pageviews": 1908176
},
"title": "Gone",
"title_with_featured": "Gone",
"url": "https://genius.com/Rose-gone-lyrics",
"primary_artist": {
"api_path": "/artists/1032508",
"header_image_url": "https://images.genius.com/57cb1380a4238e1dcc47fd14c18fc4bc.1000x500x1.jpg",
"id": 1032508,
"image_url": "https://images.genius.com/a88593efb71bc22510f0d1ec46899da5.1000x1000x1.jpg",
"is_meme_verified": false,
"is_verified": false,
"name": "ROSÉ",
"url": "https://genius.com/artists/Rose"
}
}
},
]
}
Using the dio and riverpod package, I tried to implement the following code:
Future<List<Songs>> getData() async {
Dio dio = Dio();
try{
final response = await dio.get('https://genius.p.rapidapi.com/search',
queryParameters: {'q': 'Blackpink'},
options: Options(headers: {
'X-RapidAPI-Host': 'genius.p.rapidapi.com',
'X-RapidAPI-Key': 'bf5ec94953msh94dc7db178f218cp1f29f2jsn7e7fdfb01965'
}));
final data =(response.data['hits'] as List).map((e) => Songs.fromJson(e)).toList();
return data;
} on DioError catch (err) {
print(err);
return [];
}
}
And this is my factory from Json code:
factory Songs.fromJson(Map<String, dynamic> json) {
return Songs(
title: json['title'] ,
url: json['url'] ,
artist: json['artist_names'] ,
imageUrl: json['song_art_image_url'],
);
}
You should first decode your response then access to hits in response. Here is an example query
var jsonResult = json.decode(response.data);
List<Songs> data =(jsonResult["response"]['hits'] as List<dynamic>).map((e) => Songs.fromJson(e)).toList();
First you have to Decode that Raw data then parse to the map:
var rawData=json.decode(response.data);
for(var element in rawData["response"]["hits"]){
Songs songs=Songs.fromJson(element);
}

Flutter json Unhandled Exception type

i have a problem with a json response
Json it's:
{
"SData": {
"total": "1",
"STable": {
"year": "2020",
"S1Lists": [
{
"year": "2020",
"turn": "6",
"Ranking": [
{
"position": "1",
"Person": {
"personId": "paul",
"nationality": "none"
},
},
]
}
]
}
}
Dart code
if(response.statusCode == 200){
final result = response.data;
Iterable list = result['SData'];
print(list);
}else{
throw Exception("Fail!");
}
and i receive this error
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'
how can i solve if, for example, i want to access the position field or the personId field
This happens because your json output is a Map<String, dynamic> and not a Iterable.
if (response.statusCode == 200) {
final result = response.data;
final Map<String, dynamic> map = result['SData'];
print(map );
} else {
throw Exception("Fail!");
}
Which will print this output
{
"total":1,
"STable":{
"year":2020,
"S1Lists":[
{
"year":2020,
"turn":6,
"Ranking":[
{
"position":1,
"Person":{
"personId":"paul",
"nationality":"none"
}
}
]
}
]
}
}
If you want to get the ranking.
final Map<String, dynamic> data = result ['SData'];
final Map<String, dynamic> table = data['STable']; // This is like result['SData']['STable']
final Map<String, dynamic> list = table['S1Lists']; // result['SData']['STable']['S1Lists']
final Map<String, dynamic> firstItem = list[0]; // result['SData']['STable']['S1Lists'][0]
final Map<String, dynamic> ranking = list['Ranking']; // result['SData']['STable']['S1Lists'][0]['Ranking']

in the angulardart tutorial, you can't find information on how to get data from a more complex json than in the example

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.

I'm trying to serialise the json receiving from api, but failing to do so

Whenever I'm trying to fetch data it's throwing exception:
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null.
Receiver: null
Tried calling: map<Location>(Closure: (dynamic) => Location))
print(responses) is printing null on console.
This is my function to get response from api:
String url1 = 'http://192.168.43.171:3000/location';
Future<void> showLocation() async {
var response = await http.get(Uri.encodeFull(url1));
if (response.statusCode == 200) {
print(response.body);
// Map<String, dynamic> parsedMap=jsonDecode(response.body);
final data = json.decode(response.body);
final responses = Details.fromJson(data[0]);
print(responses);
// print(parsedMap['location']);
} else {
throw Exception('failed to load');
}
}
This my locationModel.dart:
class Location {
final String latitude;
final String longitude;
Location({this.latitude, this.longitude});
factory Location.fromJson(Map<String, dynamic> parsedJson) {
return Location(
latitude: parsedJson['latitude'], longitude: parsedJson['longitude']);
}
}
class Details {
final String username;
final List<Location> locations;
Details({this.username, this.locations});
factory Details.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['locations'] as List;
print(list.runtimeType);
List<Location> locationList =
list.map((i) => Location.fromJson(i)).toList();
return Details(username: parsedJson['username'], locations: locationList);
}
}
My JSON:
[
{
"id":"ABC",
"username":"xyz",
"location":[
{
"latitude": "34",
"longitude": "343"
},
{
"latitude": "34",
"longitude": "32"
}
]
}
{
"id":"ABC1",
"username":"xyz1",
"location":[
{
"latitude": "34222",
"longitude": "32243"
},
]
}
]
You have a typo:
var list = parsedJson['locations'] as List;
vs
location:[
locations != location