Parse Json in Dart/Flutter to Entity/Model - json

Greetings
I am having this problem converting the following json to TodayWeather Entity:
How can I use the named constructor TodayHours?
I've been looking for a solution for this issue for a few days now, but I haven't found much, please guide me.
json:
{
"days": [
{
"datetime": "2023-01-05",
"datetimeEpoch": 1672864200,
"tempmax": 8.8,
"tempmin": 2.3,
"temp": 5.3,
"windspeed": 8.6,
"winddir": 223.9,
"visibility": 19.7,
"sunrise": "06:43:43",
"sunset": "16:30:24",
"conditions": "Snow, Rain, Overcast",
"hours": [
{
"datetime": "00:00:00",
"datetimeEpoch": 1672864200,
"temp": 4.4,
"humidity": 27.65,
"windspeed": 6.5,
"winddir": 249.2,
"visibility": 24.1,
"conditions": "Partially cloudy"
},
{
"datetime": "01:00:00",
"datetimeEpoch": 1672864200,
"temp": 4.4,
"humidity": 27.65,
"windspeed": 6.5,
"winddir": 249.2,
"visibility": 24.1,
"conditions": "Partially cloudy"
}
]
}
]
}
and my TodayWeather Entitiy is :
class TodayWeather {
final String datetime;
final num dateEpoch;
final String conditions;
final num tempMax;
final num tempMin;
final num windDir;
final num windSpeed;
final String sunRise;
final String sunSet;
final num humidity;
final num visibility;
final List<TodayHourse> hours;
TodayWeather.fromJson(Map<String, dynamic> json)
: datetime = json['days'][0]['datetime'],
dateEpoch = json['days'][0]['datetimeEpoch'],
conditions = json['days'][0]['conditions'],
tempMax = json['days'][0]['tempmax'],
tempMin = json['days'][0]['tempmin'],
windDir = json['days'][0]['winddir'],
windSpeed = json['days'][0]['windspeed'],
sunRise = json['days'][0]['sunrise'],
sunSet = json['days'][0]['sunset'],
humidity = json['days'][0]['humidity'],
visibility = json['days'][0]['visibility'],
hours = List<TodayHourse>.from(
json['days'][0]['hours'].map((x) => x.toJson())).toList();
}
and my TodayHours Entitiy is :
class TodayHourse {
final String datetime;
final num dateEpoch;
final String conditions;
final num temp;
final num windDir;
final num windSpeed;
final num humidity;
final num visibility;
Map<String, dynamic> toJson() => {
'datetime': datetime,
'datetimeEpoch': dateEpoch,
'conditions': conditions,
'temp': temp,
'winddir': windDir,
'windspeed': windSpeed,
'humidity': humidity,
'visibility': visibility
};
TodayHourse.fromJson(Map<String, dynamic> json)
: datetime = json['days'][0]['datetime'],
dateEpoch = json['days'][0]['datetimeEpoch'],
conditions = json['days'][0]['conditions'],
temp = json['days'][0]['temp'],
windDir = json['days'][0]['winddir'],
windSpeed = json['days'][0]['windspeed'],
humidity = json['days'][0]['humidity'],
visibility = json['days'][0]['visibility'];
}
this method is parsing Json to TodayWeather:
#override
Future<TodayWeather> getTodayWeather() async {
final response = await httpClient.get(
'36.31559%2C59.56796/today?unitGroup=metric&key=Key&contentType=json');
validResponse(response);
return TodayWeather.fromJson(response.data);
}

First change your TodayHourse.fromJson to this:
TodayHourse.fromJson(Map<String, dynamic> json)
: datetime = json['datetime'],
dateEpoch = json['datetimeEpoch'],
conditions = json['conditions'],
temp = json['temp'],
windDir = json['winddir'],
windSpeed = json['windspeed'],
humidity = json['humidity'],
visibility = json['visibility'];
your hours is list of Map and you don't need to use json['days'][0]. Then in your TodayWeather.fromJson, change hours to this:
hours = (json['days'][0]['hours'] as List).map((x) => TodayHourse.fromJson(x)).toList();
you are using wrong function instead of toJson, you need to call TodayHourse.fromJson(x).

Try to use this model:
class TodayWeather {
TodayWeather({required this.days});
final List<Day> days;
factory TodayWeather.fromJson(Map<String, dynamic> json) => TodayWeather(
days: List<Day>.from(json["days"].map((x) => Day.fromJson(x))),
);
}
class Day {
Day({
required this.datetime,
required this.datetimeEpoch,
required this.tempmax,
required this.tempmin,
required this.temp,
required this.windspeed,
required this.winddir,
required this.visibility,
required this.sunrise,
required this.sunset,
required this.conditions,
required this.hours,
});
final DateTime datetime;
final int datetimeEpoch;
final double tempmax, tempmin, temp, windspeed, winddir, visibility;
final String sunrise, sunset, conditions;
final List<Hour> hours;
factory Day.fromJson(Map<String, dynamic> json) => Day(
datetime: DateTime.parse(json["datetime"]),
datetimeEpoch: json["datetimeEpoch"],
tempmax: json["tempmax"].toDouble(),
tempmin: json["tempmin"].toDouble(),
temp: json["temp"].toDouble(),
windspeed: json["windspeed"].toDouble(),
winddir: json["winddir"].toDouble(),
visibility: json["visibility"].toDouble(),
sunrise: json["sunrise"],
sunset: json["sunset"],
conditions: json["conditions"],
hours: List<Hour>.from(json["hours"].map((x) => Hour.fromJson(x))),
);
}
class Hour {
Hour({
required this.datetime,
required this.datetimeEpoch,
required this.temp,
required this.humidity,
required this.windspeed,
required this.winddir,
required this.visibility,
required this.conditions,
});
final int datetimeEpoch;
final double temp, humidity, windspeed, winddir, visibility;
final String datetime, conditions;
factory Hour.fromJson(Map<String, dynamic> json) => Hour(
datetime: json["datetime"],
datetimeEpoch: json["datetimeEpoch"],
temp: json["temp"].toDouble(),
humidity: json["humidity"].toDouble(),
windspeed: json["windspeed"].toDouble(),
winddir: json["winddir"].toDouble(),
visibility: json["visibility"].toDouble(),
conditions: json["conditions"],
);
}

First of all for more clear way to parse JSON arrays you can create helper method in your models, I call it Model.fromJsonList
static List<WeatherDay> fromJsonList(dynamic jsonList) {
if (jsonList == null || jsonList.isEmpty) return [];
return (jsonList as List).map((e) => WeatherDay.fromJson(e)).toList();
}
So by this method you can parse array response very easy and clean for example:
Future<WeatherDay> fetchTodayWeather() async {
final response = await httpClient.get(
'36.31559%2C59.56796/today?unitGroup=metric&key=Key&contentType=json');
final List<WeatherDay> weatherDays = WeatherDay.fromJsonList(response.data["days"]);
return weatherDays.first;
}
Totally we have:
class WeatherDay {
WeatherDay( {
#required this.datetime,
#required this.hours,
});
final String datetime;
final List<WeatherHour> hours;
factory WeatherDay.fromJson(Map<String, dynamic> json) {
return WeatherDay(
datetime: json['datetime'] as String,
hours: WeatherHour.fromJsonList(json['hours']),
);
}
static List<WeatherDay> fromJsonList(dynamic jsonList) {
if (jsonList == null || jsonList.isEmpty) return [];
return (jsonList as List).map((e) => WeatherDay.fromJson(e)).toList();
}
}
class WeatherHour {
WeatherHour( {
#required this.dateEpoch,
#required this.conditions,
});
final num dateEpoch;
final String conditions;
factory WeatherHour.fromJson(Map<String, dynamic> json) {
return WeatherHour(
dateEpoch: json['datetimeEpoch'] as num,
conditions: json['conditions'] as String,
);
}
static List<WeatherHour> fromJsonList(dynamic jsonList) {
if (jsonList == null || jsonList.isEmpty) return [];
return (jsonList as List).map((e) => WeatherHour.fromJson(e)).toList();
}
}
Note: I didn't parse all variable, do it by yourself.

Related

Use json in the filter

Hi guys I have an api I use that responds like this:
responds
{
"RAW": {
"BTC": {
"USD": {
"TYPE": "5",
"MARKET": "CCCAGG",
"FROMSYMBOL": "BTC",
"TOSYMBOL": "USD",
"FLAGS": "1026",
"PRICE": 41091.49,
"LASTUPDATE": 1649873443,
"MEDIAN": 41085.18,
"LASTVOLUME": 0.001056,
"LASTVOLUMETO": 43.38595008,
Now to convert and use it in darts (modeling) we have to do the mapping operation, right? Does anyone know how to do this when this response is nested! I did it, but I know it's not right
My code
class CryptoEntity {
final String basecode;
// final String targetcod;
final int price;
final int volume;
final int change;
CryptoEntity.fromjason(Map<String, dynamic> jason)
: basecode = jason['FROMSYMBOL'],
// targetcod = jason['target'],
price = jason['PRICE'],
volume = jason['VOLUMEDAY'],
change = jason['LASTVOLUME'];
}
Use freezed package and json serializable for code generation, it is good for the long term development but this requires basic knowledge in flutter.
Use Online JSON to Dart converter, this site generates null safety dart class. With this solution, all you need is to change the class names after each conversion manually, and note for the fromJson factory constructor method and toJson class method.
try this:
class CryptoEntity {
final String? basecode; // ? => means that this field can be null
// final String targetcod;
final int? price;
final int? volume;
final int? change;
//constroctor
CryptoEntity(this.basecode, this.price, .. );
factory CryptoEntity.fromjason(Map<String, dynamic> jason){
return CryptoEntity(
price = jason['PRICE'],
volume = jason['VOLUMEDAY'],
change = jason['LASTVOLUME'];
);
}
}
You can turn the json into an object
import 'dart:convert';
MyModel myModelFromMap(String str) => MyModel.fromMap(json.decode(str));
String myModelToMap(MyModel data) => json.encode(data.toMap());
class MyModel {
MyModel({
required this.raw,
});
Raw raw;
factory MyModel.fromMap(Map<String, dynamic> json) => MyModel(
raw: Raw.fromMap(json["RAW"]),
);
Map<String, dynamic> toMap() => {
"RAW": raw.toMap(),
};
}
class Raw {
Raw({
required this.btc,
});
Btc btc;
factory Raw.fromMap(Map<String, dynamic> json) => Raw(
btc: Btc.fromMap(json["BTC"]),
);
Map<String, dynamic> toMap() => {
"BTC": btc.toMap(),
};
}
class Btc {
Btc({
required this.usd,
});
Usd usd;
factory Btc.fromMap(Map<String, dynamic> json) => Btc(
usd: Usd.fromMap(json["USD"]),
);
Map<String, dynamic> toMap() => {
"USD": usd.toMap(),
};
}
class Usd {
Usd({
required this.type,
required this.market,
required this.fromsymbol,
required this.tosymbol,
required this.flags,
required this.price,
required this.lastupdate,
required this.median,
required this.lastvolume,
required this.lastvolumeto,
});
String type;
String market;
String fromsymbol;
String tosymbol;
String flags;
double price;
int lastupdate;
double median;
double lastvolume;
double lastvolumeto;
factory Usd.fromMap(Map<String, dynamic> json) => Usd(
type: json["TYPE"],
market: json["MARKET"],
fromsymbol: json["FROMSYMBOL"],
tosymbol: json["TOSYMBOL"],
flags: json["FLAGS"],
price: json["PRICE"].toDouble(),
lastupdate: json["LASTUPDATE"],
median: json["MEDIAN"].toDouble(),
lastvolume: json["LASTVOLUME"].toDouble(),
lastvolumeto: json["LASTVOLUMETO"].toDouble(),
);
Map<String, dynamic> toMap() => {
"TYPE": type,
"MARKET": market,
"FROMSYMBOL": fromsymbol,
"TOSYMBOL": tosymbol,
"FLAGS": flags,
"PRICE": price,
"LASTUPDATE": lastupdate,
"MEDIAN": median,
"LASTVOLUME": lastvolume,
"LASTVOLUMETO": lastvolumeto,
};
}
You can use it like this
MyModel myModel = myModelFromMap(jsonDecode(json));
https://app.quicktype.io/

Flutter How to parse Api response?

Im working with rawg.io api and trying to get datas about games. There is a problem which i think it's about parsing data from json. I worked with easy apis which has not arrays or maps in it. But this data complicated and i guess that's why im getting always null results while try to print datas to screen.
Here is my code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:video_games/load_data.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Future<Welcome> apiCall() async {
final response = await http.get(Uri.parse(
'https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56'));
print(response.statusCode);
print(response.body);
return Welcome.fromJson(jsonDecode(response.body));
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder<Welcome>(
future: apiCall(),
builder: (context, snapshot) {
// var growableList = [];
// List<Result> data = snapshot.data!.results;
// growableList.add(data[0].name);
return Text('${snapshot.data!.count}');
},
),
),
);
}
}
That is my response body and status code without using in a widget or parsing it
I/flutter ( 3666): 200
I/flutter ( 3666): {"count":679153,"next":"https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56&page=2","previous":null,"results":[{"id":3498,"slug":"grand-theft-auto-v","name":"Grand Theft Auto V","released":"2013-09-17","tba":false,"background_image":"https://media.rawg.io/media/games/456/456dea5e1c7e3cd07060c14e96612001.jpg","rating":4.48,"rating_top":5,"ratings":[{"id":5,"title":"exceptional","count":3217,"percent":58.97},{"id":4,"title":"recommended","count":1800,"percent":33.0},{"id":3,"title":"meh","count":348,"percent":6.38},{"id":1,"title":"skip","count":90,"percent":1.65}],"ratings_count":5389,"reviews_text_count":36,"added":16689,"added_by_status":{"yet":415,"owned":9874,"beaten":4491,"toplay":474,"dropped":835,"playing":600},"metacritic":97,"playtime":71,"suggestions_count":402,"updated":"2021-08-20T12:42:02","user_game":null,"reviews_count":5455,"saturated_color":"0f0f0f","dominant_color":"0f0f0f","platforms":[{"platform":{"id":1,"name":"Xbox One","slug":"xbox-one","image":null,"year_end":null,"year_
And this is my data class
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
required this.count,
required this.next,
required this.previous,
required this.results,
});
int count;
String next;
String previous;
List<Result> results;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
count: json["count"],
next: json["next"],
previous: json["previous"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"count": count,
"next": next,
"previous": previous,
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
Result({
required this.id,
required this.slug,
required this.name,
required this.released,
required this.tba,
required this.backgroundImage,
required this.rating,
required this.ratingTop,
required this.ratings,
required this.ratingsCount,
required this.reviewsTextCount,
required this.added,
required this.addedByStatus,
required this.metacritic,
required this.playtime,
required this.suggestionsCount,
required this.updated,
required this.esrbRating,
required this.platforms,
});
int id;
String slug;
String name;
DateTime released;
bool tba;
String backgroundImage;
int rating;
int ratingTop;
AddedByStatus ratings;
int ratingsCount;
String reviewsTextCount;
int added;
AddedByStatus addedByStatus;
int metacritic;
int playtime;
int suggestionsCount;
DateTime updated;
EsrbRating esrbRating;
List<Platform> platforms;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
slug: json["slug"],
name: json["name"],
released: DateTime.parse(json["released"]),
tba: json["tba"],
backgroundImage: json["background_image"],
rating: json["rating"],
ratingTop: json["rating_top"],
ratings: AddedByStatus.fromJson(json["ratings"]),
ratingsCount: json["ratings_count"],
reviewsTextCount: json["reviews_text_count"],
added: json["added"],
addedByStatus: AddedByStatus.fromJson(json["added_by_status"]),
metacritic: json["metacritic"],
playtime: json["playtime"],
suggestionsCount: json["suggestions_count"],
updated: DateTime.parse(json["updated"]),
esrbRating: EsrbRating.fromJson(json["esrb_rating"]),
platforms: List<Platform>.from(
json["platforms"].map((x) => Platform.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"slug": slug,
"name": name,
"released":
"${released.year.toString().padLeft(4, '0')}-${released.month.toString().padLeft(2, '0')}-${released.day.toString().padLeft(2, '0')}",
"tba": tba,
"background_image": backgroundImage,
"rating": rating,
"rating_top": ratingTop,
"ratings": ratings.toJson(),
"ratings_count": ratingsCount,
"reviews_text_count": reviewsTextCount,
"added": added,
"added_by_status": addedByStatus.toJson(),
"metacritic": metacritic,
"playtime": playtime,
"suggestions_count": suggestionsCount,
"updated": updated.toIso8601String(),
"esrb_rating": esrbRating.toJson(),
"platforms": List<dynamic>.from(platforms.map((x) => x.toJson())),
};
}
class AddedByStatus {
AddedByStatus();
factory AddedByStatus.fromJson(Map<String, dynamic> json) => AddedByStatus();
Map<String, dynamic> toJson() => {};
}
class EsrbRating {
EsrbRating({
required this.id,
required this.slug,
required this.name,
});
int id;
String slug;
String name;
factory EsrbRating.fromJson(Map<String, dynamic> json) => EsrbRating(
id: json["id"],
slug: json["slug"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"slug": slug,
"name": name,
};
}
class Platform {
Platform({
required this.platform,
required this.releasedAt,
required this.requirements,
});
EsrbRating platform;
String releasedAt;
Requirements requirements;
factory Platform.fromJson(Map<String, dynamic> json) => Platform(
platform: EsrbRating.fromJson(json["platform"]),
releasedAt: json["released_at"],
requirements: Requirements.fromJson(json["requirements"]),
);
Map<String, dynamic> toJson() => {
"platform": platform.toJson(),
"released_at": releasedAt,
"requirements": requirements.toJson(),
};
}
class Requirements {
Requirements({
required this.minimum,
required this.recommended,
});
String minimum;
String recommended;
factory Requirements.fromJson(Map<String, dynamic> json) => Requirements(
minimum: json["minimum"],
recommended: json["recommended"],
);
Map<String, dynamic> toJson() => {
"minimum": minimum,
"recommended": recommended,
};
}
Things i tried;
tried to convert response body to string before parsing
tried to change my widget to asnyc
tried to simplify my data class (to avoid arrays)
My opinion after research,
return Welcome.fromJson(jsonDecode(response.body));
this part can't work correctly cause of json decode can't decode complex datas which is has arrays and maps.
I stuck at this point and struggling. There is no document that i can do it correctly. Please help me about this.

cannot resolve type 'String' is not a subtype of type 'int' of 'index'

i started having an issue recently. I need to parse my json response to a list to my model object class but i keep getting this error:
type 'String' is not a subtype of type 'int' of 'index'
tried several solutions online but it didn't work for me. I was thing my variable declarations in my model class was the issue so i changed them to dynamic but didnt still work for me.
Heading
Model
class MenteeIndex {
dynamic id;
dynamic mentor_id;
dynamic mentee_id;
dynamic status;
dynamic session_count;
dynamic current_job;
dynamic email;
dynamic phone_call;
dynamic video_call;
dynamic face_to_face;
dynamic created_at;
dynamic updated_at;
MenteeIndex(this.id, this.mentor_id, this.mentee_id, this.status, this.session_count, this.current_job,
this.email, this.phone_call, this.video_call, this.face_to_face, this.created_at, this.updated_at);
Map<String, dynamic> toJson() => {
'id': id,
'mentor_id': mentor_id,
'mentee_id': mentee_id,
'status': status,
'session_count': session_count,
'current_job': current_job,
'email':email,
'phone_call': phone_call,
'video_call': video_call,
'face_to_face': face_to_face,
'created_at': created_at,
'updated_at': updated_at,
};
MenteeIndex.fromJson(Map<String, dynamic> json):
id = json['id'],
mentor_id = json['mentor_id'],
mentee_id = json['mentee_id'],
status = json['status'],
session_count = json['session_count'],
current_job = json['current_job'],
email = json['email'],
phone_call = json['phone_call'],
video_call = json['video_call'],
face_to_face = json['face_to_face'],
created_at = json['created_at'],
updated_at = json['updated_at'];
}
Main
Future fetchIndex() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host + AuthUtils.endPointIndex;
try {
final response = await http.get(
uri,
headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': 'Bearer ' + sharedPreferences.get("token"), },
);
var encodeFirst = json.encode(response.body);
final responseJson = json.decode(encodeFirst);
//here is where the error is
for (var u in responseJson["data"]) {
MenteeIndex user = MenteeIndex(
u["id"],
u["mentor_id"],
u["mentee_id"],
u["status"],
u["session_count"],
u["current_job"],
u["email"],
u["phone_call"],
u["video_call"],
u["face_to_face"],
u["created_at"],
u["updated_at"]);
menteeIndexes.add(user);
setState((){
mentorIdList = menteeIndexes.map((MenteeIndex) => MenteeIndex.mentor_id);
indexIds = menteeIndexes.map((MenteeIndex) => MenteeIndex.id);
status = menteeIndexes.map((MenteeIndex) => MenteeIndex.status);
});
}
return responseJson;
} catch (exception) {
print(exception);
}
}
Response/Error
{"current_page":1,"data":[{"id":13,"mentor_id":"5","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-20 20:37:50","updated_at":"2020-02-20 20:37:50"},{"id":14,"mentor_id":"8","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-21 22:39:31","updated_at":"2020-02-21 22:39:31"},{"id":15,"mentor_id":"10","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:15:23","updated_at":"2020-02-23 05:15:23"},{"id":16,"mentor_id":"191","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:17:34","updated_at":"2020-02-23 05:17:34"},{"id":17,"mentor_id":"141","mentee_id":"184","status":"1",
I/flutter (20995): type 'String' is not a subtype of type 'int' of 'index'
Decode the response body to Map
final responseJson = json.decode(response.body);
Convert the Map list to MenteeIndex list
final menteeIndexes = responseJson["data"].map(
(json) => MenteeIndex.fromJson(json)
).toList();
Check out this model class
// To parse this JSON data, do
//
// final yourModel = yourModelFromJson(jsonString);
import 'dart:convert';
YourModel yourModelFromJson(String str) => YourModel.fromJson(json.decode(str));
String yourModelToJson(YourModel data) => json.encode(data.toJson());
class YourModel {
int currentPage;
List<Datum> data;
YourModel({
this.currentPage,
this.data,
});
factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
currentPage: json["current_page"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"current_page": currentPage,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
int id;
String mentorId;
String menteeId;
dynamic status;
int sessionCount;
dynamic currentJob;
dynamic email;
dynamic phoneCall;
dynamic videoCall;
dynamic faceToFace;
DateTime createdAt;
DateTime updatedAt;
Datum({
this.id,
this.mentorId,
this.menteeId,
this.status,
this.sessionCount,
this.currentJob,
this.email,
this.phoneCall,
this.videoCall,
this.faceToFace,
this.createdAt,
this.updatedAt,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
mentorId: json["mentor_id"],
menteeId: json["mentee_id"],
status: json["status"],
sessionCount: json["session_count"],
currentJob: json["current_job"],
email: json["email"],
phoneCall: json["phone_call"],
videoCall: json["video_call"],
faceToFace: json["face_to_face"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"mentor_id": mentorId,
"mentee_id": menteeId,
"status": status,
"session_count": sessionCount,
"current_job": currentJob,
"email": email,
"phone_call": phoneCall,
"video_call": videoCall,
"face_to_face": faceToFace,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
Just insert you response.body to this method :
final yourModel = yourModelFromJson(response.body);
you can just get the list of data using below call :
List<Datum> dataList = List();
dataList = yourModel.data;
here you get the list of data
You will get your Single object from it and then depending on that you can do what ever you want.

get value from nested json array and check if it is empty or not in flutter

My json array looks like:
[
{
"sub_categories": [],
"category_id": "82",
"catgory_name": "Andrew Murray 1 Month",
"parent_cat_id": "1"
},
{
"sub_categories": [
{
"category_id": "177",
"catgory_name": "2 Samuel",
"parent_cat_id": "167"
}
],
"category_id": "167",
"catgory_name": "The Bible ASV",
"parent_cat_id": "1"
},
]
First i want to display "catgory_name" in listview and if that catgory_name has sub_categories array than i need to display it in another list , so how can i achieve this.
i get all catgory_name by following code:
class CategoryModel {
final String name;
final List<SubCategoryModel> SubCategory;
CategoryModel({
this.name,
this.SubCategory,
});
factory CategoryModel.fromJson(Map<String, dynamic> json) {
return new CategoryModel(
name: json['catgory_name'].toString(),
SubCategory: parsesub_categories(json['sub_categories']),
// SubCategory:(json['sub_categories'] as List).map((map) => map).toList(),
);
}
static List<SubCategoryModel> parsesub_categories(cateJson) {
List<SubCategoryModel> catlist = new List<SubCategoryModel>.from(cateJson);
return catlist;
}
but sub_categories i could not get that array .
You can create data model as below:
class CategoryModel {
List<SubCateogryModel> subCategories;
String categoryId;
String catgoryName;
String parentCatId;
CategoryModel(
{this.subCategories,
this.categoryId,
this.catgoryName,
this.parentCatId});
CategoryModel.fromJson(Map<String, dynamic> json) {
if (json['sub_categories'] != null) {
subCategories = new List<SubCateogryModel>();
json['sub_categories'].forEach((v) {
subCategories.add(new SubCateogryModel.fromJson(v));
});
}
categoryId = json['category_id'];
catgoryName = json['catgory_name'];
parentCatId = json['parent_cat_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.subCategories != null) {
data['sub_categories'] =
this.subCategories.map((v) => v.toJson()).toList();
}
data['category_id'] = this.categoryId;
data['catgory_name'] = this.catgoryName;
data['parent_cat_id'] = this.parentCatId;
return data;
}
}
class SubCateogryModel {
String categoryId;
String catgoryName;
String parentCatId;
SubCateogryModel({this.categoryId, this.catgoryName, this.parentCatId});
SubCateogryModel.fromJson(Map<String, dynamic> json) {
categoryId = json['category_id'];
catgoryName = json['catgory_name'];
parentCatId = json['parent_cat_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['category_id'] = this.categoryId;
data['catgory_name'] = this.catgoryName;
data['parent_cat_id'] = this.parentCatId;
return data;
}
}
Now, you have to parse your json array into Data model array
List<CategoryModel> categoryList = [];
jsonArray.forEach((val){
categoryList.add(CategoryModel.fromJson(val));
});
Now, the UI code,
ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text(categoryList[index].catgoryName),
subtitle: categoryList[index].subCategories.isNotEmpty
? Column(
children: List.generate(
categoryList[index].subCategories.length, (position) {
String subCategory = categoryList[index]
.subCategories[position]
.catgoryName;
return Text(subCategory);
}),
)
: SizedBox(),
);
},
itemCount: categoryList.length,
)
You can use QuickType.io to generate dart classes (PODOs) for json.
import 'dart:convert';
List<CategoryModel> categoryModelFromJson(String str) => List<CategoryModel>.from(json.decode(str).map((x) => CategoryModel.fromJson(x)));
String categoryModelToJson(List<CategoryModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CategoryModel {
List<CategoryModel> subCategories;
String categoryId;
String catgoryName;
String parentCatId;
CategoryModel({
this.subCategories,
this.categoryId,
this.catgoryName,
this.parentCatId,
});
factory CategoryModel.fromJson(Map<String, dynamic> json) => CategoryModel(
subCategories: json["sub_categories"] == null ? null : List<CategoryModel>.from(json["sub_categories"].map((x) => CategoryModel.fromJson(x))),
categoryId: json["category_id"],
catgoryName: json["catgory_name"],
parentCatId: json["parent_cat_id"],
);
Map<String, dynamic> toJson() => {
"sub_categories": subCategories == null ? null : List<dynamic>.from(subCategories.map((x) => x.toJson())),
"category_id": categoryId,
"catgory_name": catgoryName,
"parent_cat_id": parentCatId,
};
}

flutter : nested json parsing list

I am trying to call Name and Fees from my json code
it is nested array from main array of my json the main array i can deal with it but the sub array i can't
"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
],
And I can't do that because of the error here when iam tring to call 'Name' and 'Fees'
type 'List<ExtraServices>' is not a subtype of type 'String'
and this is my class for mapping tour guide data to use it in list view
class TourGuide{
String id;
String name;
String email;
String password;
List<ExtraServices> extraService;
TourGuide({
this.id,
this.name,
this.email,
this.password,
this.extraService,
});
TourGuide.fromJson(Map<String, dynamic> json){
List<dynamic> extra = json['guideExtraServices'];
List<ExtraServices> extraList = extra.map((i) => ExtraServices.fromJson(i)).toList();
id = json['id'].toString();
name = json['displayName'];
email = json['email'];
password = json['password'];
extraService=extraList;
}
}
and this is a Extra Services class which tour guide class depend on to get the sub array
class ExtraServices{
String name;
double fees;
ExtraServices({
this.name,
this.fees
});
ExtraServices.fromJson(Map<String, dynamic> json){
name = json['Name'];
fees = json['Fees'].toDouble();
}
}
my provider method for decode json using for api
Future<dynamic> tourGuideList() async {
_isLoading = true;
notifyListeners();
print('Starting request');
http.Response response = await http.get(Environment.tourGuide,
headers: Environment.requestHeader);
print('Completed request');
print('respond data : ${response.body}');
Map<String, dynamic> res = json.decode(response.body);
var results;
if (res['code'] == 200) {
print('start load tourguide');
_tourGuide = [];
res['message'].forEach((v) {
_tourGuide.add(new TourGuide.fromJson(v));
});
results = true;
} else {
results =
FailedRequest(code: 400, message: res['error'], status: false);
}
_isLoading = false;
notifyListeners();
return results;
}
and I don't know why I have an error and I can't fix it
I think your json should be like this in total:
{"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
]}
Try
// To parse this JSON data, do
//
// final tourGuide = tourGuideFromJson(jsonString);
import 'dart:convert';
TourGuide tourGuideFromJson(String str) => TourGuide.fromJson(json.decode(str));
String tourGuideToJson(TourGuide data) => json.encode(data.toJson());
class TourGuide {
List<GuideExtraService> guideExtraServices;
TourGuide({
this.guideExtraServices,
});
factory TourGuide.fromJson(Map<String, dynamic> json) => TourGuide(
guideExtraServices: List<GuideExtraService>.from(json["guideExtraServices"].map((x) => GuideExtraService.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"guideExtraServices": List<dynamic>.from(guideExtraServices.map((x) => x.toJson())),
};
}
class GuideExtraService {
String name;
int fees;
GuideExtraService({
this.name,
this.fees,
});
factory GuideExtraService.fromJson(Map<String, dynamic> json) => GuideExtraService(
name: json["Name"],
fees: json["Fees"],
);
Map<String, dynamic> toJson() => {
"Name": name,
"Fees": fees,
};
}
Please try the below code :-
First Create Model :-
class GuideResponseModel {
List<GuideExtraServicesModel> guideExtraServiceList;
GuideResponseModel({
this.guideExtraServiceList
});
factory GuideResponseModel.fromJson(Map<String, dynamic> parsedJson) {
try {
List<GuideExtraServicesModel> guideExtraServiceModelList = new List();
if (parsedJson.containsKey('guideExtraServices')) {
var countryList = parsedJson['guideExtraServices'] as List;
guideExtraServiceModelList =
countryList.map((i) => GuideExtraServicesModel.fromJson(i)).toList();
}
return GuideResponseModel(
guideExtraServiceList: guideExtraServiceModelList
);
} catch (e) {
return null;
}
}
}
class GuideExtraServicesModel {
String name;
int fees;
GuideExtraServicesModel({this.name,this.fees});
factory GuideExtraServicesModel.fromJson(Map<String, dynamic> json) {
return GuideExtraServicesModel(name: json['Name'],fees: json['Fees']);
}
}
Second User the Model:-
String jsonData = '{"guideExtraServices": [{"Name": "Limousine","Fees": 100},{"Name": "Bus","Fees": 10000},{"Name": "Mini-Bus","Fees": 5000}]}';
final dynamic jsonResponse = json.decode(jsonData);
final GuideResponseModel responseModel = GuideResponseModel.fromJson(jsonResponse);
print('======${responseModel.guideExtraServiceList[0].name}----${responseModel.guideExtraServiceList[0].fees}');