I am using dio by using this I am passing form data and getting response but I am unable to store data to object. Please help me
It is giving response when I am printing response.data but I am not getting how to store the response to object.
class MainActivityGrid extends StatefulWidget {
#override
_MainActivityGridState createState() => _MainActivityGridState();
}
class _MainActivityGridState extends State<MainActivityGrid> {
// List<ImageModel>images= [];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold(
appBar: AppBar(
title: new Text("IPTV"),
),
body: new Center(
child: new RaisedButton(
child: new Text("Button"), onPressed: fetchImage),
),
),
);
}
Future<String> fetchImage() async {
String url = "http://xxxxxx:xxx/onnet_api/mediaList.php";
Response response;
Dio dio = new Dio();
FormData formData = new FormData.from(
{"publisherid": 102, "tag": "media", "subtag": "list"});
// counter ++;
response = await dio.post(url, data: formData);
// dio.interceptors.add(LogInterceptor(responseBody: fa));
//int status = response.data["status"]["data"];
//Map responseBody = response.data;
//loginResponse = new LoginResponse.fromJson(json.decode(response.data));
print(response.data["data"][0]);
//ImageModel imageModel = new ImageModel.fromJson(json.decode(response.data[]));
//print('response media: $status');
/* setState(() {
//images.add(imageModel);
});*/
}
}
my JSON response for my API is showing like this below: please try to help me in this.
{
"status": 1,
"data": [
{
"id": "0_314t2peg",
"name": "Countdown",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_314t2peg/version/100002",
"plays": 12,
"categories": "News>BBC,News>CNBC,News>PublicTV,News>TV9,Shows>Thriller,Shows>Regional",
"categoriesIds": "19,20,18,17,13,16",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_314t2peg/format/url/protocol/http",
"duration": 13,
"createdAt": "28/11/18 11:26:39",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_joyzmp2z",
"name": "voice 4k",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_joyzmp2z/version/100002",
"plays": 14,
"categories": "News>BBC,News>CNBC,News>PublicTV,News>TV9,Shows>Thriller,Shows>Regional",
"categoriesIds": "19,20,18,17,13,16",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_joyzmp2z/format/url/protocol/http",
"duration": 20,
"createdAt": "28/11/18 11:25:56",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_yndwskxv",
"name": "news",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_yndwskxv/version/100012",
"plays": 6,
"categories": "News>BBC,News>TV9,Shows>Regional",
"categoriesIds": "19,17,16",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_yndwskxv/format/url/protocol/http",
"duration": 17,
"createdAt": "28/11/18 11:24:12",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_jd7hul0b",
"name": "GB10Sec",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_jd7hul0b/version/100002",
"plays": 8,
"categories": "Shows>Thriller,Shows>Action,Shows>Sci-Fi",
"categoriesIds": "13,15,14",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_jd7hul0b/format/url/protocol/http",
"duration": 10,
"createdAt": "28/11/18 11:14:40",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_bz9qlkle",
"name": "Thugs Of Hindostan",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_bz9qlkle/version/100002",
"plays": 0,
"categories": null,
"categoriesIds": null,
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_bz9qlkle/format/url/protocol/http",
"duration": 218,
"createdAt": "28/11/18 11:08:45",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_swm5unow",
"name": "Shivaay",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_swm5unow/version/100002",
"plays": 0,
"categories": null,
"categoriesIds": null,
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_swm5unow/format/url/protocol/http",
"duration": 230,
"createdAt": "28/11/18 11:08:23",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_1n1qg0hq",
"name": "Rocky Handsome",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_1n1qg0hq/version/100012",
"plays": 9,
"categories": "Movies>Drama,Movies>Sci-Fi",
"categoriesIds": "22,24",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_1n1qg0hq/format/url/protocol/http",
"duration": 184,
"createdAt": "28/11/18 11:08:03",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_3vk4o4ie",
"name": "Genius",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_3vk4o4ie/version/100012",
"plays": 5,
"categories": "Movies>Drama,Movies>Sci-Fi",
"categoriesIds": "22,24",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_3vk4o4ie/format/url/protocol/http",
"duration": 200,
"createdAt": "28/11/18 11:07:46",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_jb8en5kn",
"name": "Commando",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_jb8en5kn/version/100012",
"plays": 2,
"categories": "Movies>Thriller,Movies>Drama,Movies>Sci-Fi",
"categoriesIds": "23,22,24",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_jb8en5kn/format/url/protocol/http",
"duration": 162,
"createdAt": "28/11/18 11:07:25",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_es5vzzca",
"name": "Action Jackson",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_es5vzzca/version/100002",
"plays": 0,
"categories": "Movies>Thriller,Movies>Drama,Movies>Sci-Fi",
"categoriesIds": "23,22,24",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_es5vzzca/format/url/protocol/http",
"duration": 175,
"createdAt": "28/11/18 11:06:13",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_2tfugvsm",
"name": "jellyfish-25-mbps-hd-hevc",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_2tfugvsm/version/100002",
"plays": 0,
"categories": null,
"categoriesIds": null,
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_2tfugvsm/format/url/protocol/http",
"duration": 30,
"createdAt": "22/11/18 09:05:26",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_z5i5fmiw",
"name": "small (3)",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_z5i5fmiw/version/100022",
"plays": 1,
"categories": null,
"categoriesIds": null,
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_z5i5fmiw/format/url/protocol/http",
"duration": 6,
"createdAt": "22/11/18 06:41:15",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_0i4hbs9o",
"name": "dolbycanyon",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_0i4hbs9o/version/100012",
"plays": 1,
"categories": null,
"categoriesIds": null,
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_0i4hbs9o/format/url/protocol/http",
"duration": 38,
"createdAt": "22/11/18 06:38:13",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_wbd3wu38",
"name": "Mary and little lamb",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_wbd3wu38/version/100002",
"plays": 3,
"categories": "Shows>Sci-Fi,Shows>Regional,Movies>Action",
"categoriesIds": "14,16,21",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_wbd3wu38/format/url/protocol/http",
"duration": 184,
"createdAt": "12/11/18 10:36:17",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_k4unuqi2",
"name": "Johny Johny",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_k4unuqi2/version/100002",
"plays": 2,
"categories": "Shows>Sci-Fi,Movies>Action",
"categoriesIds": "14,21",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_k4unuqi2/format/url/protocol/http",
"duration": 186,
"createdAt": "12/11/18 10:36:17",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_3w4xjt5x",
"name": "One Little Flower",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_3w4xjt5x/version/100012",
"plays": 7,
"categories": "TV>Entertainment",
"categoriesIds": "25",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_3w4xjt5x/format/url/protocol/http",
"duration": 83,
"createdAt": "12/11/18 10:20:14",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_w64yjfen",
"name": "I'm A Little Teapot",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_w64yjfen/version/100012",
"plays": 9,
"categories": "Shows>Action,TV>Shows",
"categoriesIds": "15,11",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_w64yjfen/format/url/protocol/http",
"duration": 104,
"createdAt": "12/11/18 10:20:14",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_591qnfyf",
"name": "Little Jack Horner",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_591qnfyf/version/100002",
"plays": 93,
"categories": "Shows>Regional,Movies>Action,TV>Shows",
"categoriesIds": "16,21,11",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_591qnfyf/format/url/protocol/http",
"duration": 87,
"createdAt": "12/11/18 10:18:49",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_n1wvco0o",
"name": "My School",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_n1wvco0o/version/100012",
"plays": 21,
"categories": "TV>Shows",
"categoriesIds": "11",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_n1wvco0o/format/url/protocol/http",
"duration": 75,
"createdAt": "12/11/18 10:18:49",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_srtxu635",
"name": "Hop a little",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_srtxu635/version/100012",
"plays": 24,
"categories": "Movies>Thriller,Movies>Action,TV>Shows",
"categoriesIds": "23,21,11",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_srtxu635/format/url/protocol/http",
"duration": 108,
"createdAt": "12/11/18 10:18:49",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_uuu7jii2",
"name": "Come Little Children",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_uuu7jii2/version/100002",
"plays": 4,
"categories": "Movies>Sci-Fi,Movies>Action,TV>Shows",
"categoriesIds": "24,21,11",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_uuu7jii2/format/url/protocol/http",
"duration": 94,
"createdAt": "12/11/18 10:16:00",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_9ld6kzph",
"name": "story telling",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_9ld6kzph/version/100002",
"plays": 2,
"categories": "Movies>Drama,Movies>Action",
"categoriesIds": "22,21",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_9ld6kzph/format/url/protocol/http",
"duration": 73,
"createdAt": "12/11/18 10:16:00",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_cz6egmc9",
"name": "Tenali Raman In English",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_cz6egmc9/version/100002",
"plays": 1,
"categories": "Movies>Action,Shows>Thriller",
"categoriesIds": "21,13",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_cz6egmc9/format/url/protocol/http",
"duration": 151,
"createdAt": "12/11/18 10:16:00",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_pj8ansdd",
"name": "The two frogs",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_pj8ansdd/version/100002",
"plays": 1,
"categories": "News>TV9,Movies>Action",
"categoriesIds": "17,21",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_pj8ansdd/format/url/protocol/http",
"duration": 141,
"createdAt": "12/11/18 10:16:00",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_7wy5icdl",
"name": "Twinkle Twinkle",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_7wy5icdl/version/100002",
"plays": 1,
"categories": "News>CNBC",
"categoriesIds": "20",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_7wy5icdl/format/url/protocol/http",
"duration": 181,
"createdAt": "12/11/18 10:16:00",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_0l7xkwee",
"name": "Two little hands",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_0l7xkwee/version/100002",
"plays": 5,
"categories": "Movies>Action,News>BBC",
"categoriesIds": "21,19",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_0l7xkwee/format/url/protocol/http",
"duration": 59,
"createdAt": "12/11/18 10:16:00",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_58md9gkm",
"name": "amazoneco",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_58md9gkm/version/100002",
"plays": 0,
"categories": "News>PublicTV",
"categoriesIds": "18",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_58md9gkm/format/url/protocol/http",
"duration": 36,
"createdAt": "05/11/18 12:01:44",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_f90klu3n",
"name": "arunicecream",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_f90klu3n/version/100012",
"plays": 2,
"categories": null,
"categoriesIds": null,
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_f90klu3n/format/url/protocol/http",
"duration": 15,
"createdAt": "05/11/18 12:01:44",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_hmr8atha",
"name": "bahubalitrailer",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_hmr8atha/version/100012",
"plays": 11,
"categories": "TV>Songs,Shows>Thriller,Shows>Regional",
"categoriesIds": "12,13,16",
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_hmr8atha/format/url/protocol/http",
"duration": 21,
"createdAt": "05/11/18 12:01:44",
"status": 2,
"statusc": 2,
"mediaType": 1
},
{
"id": "0_kzwqw8eq",
"name": "BigData",
"thumbnailUrl": "http://onnet-video-platform/p/102/sp/10200/thumbnail/entry_id/0_kzwqw8eq/version/100012",
"plays": 1,
"categories": null,
"categoriesIds": null,
"dataUrl": "http://159.65.156.204/p/102/sp/10200/playManifest/entryId/0_kzwqw8eq/format/url/protocol/http",
"duration": 93,
"createdAt": "05/11/18 12:01:44",
"status": 2,
"statusc": 2,
"mediaType": 1
}
],
"totalRecord": 30
}
No need to use Json Decode for Dio. You can do something like below:
Response responseval=await dio.post(url,options: Options(headers: headers));
var name=responseval.data['username'];
var id=responseeval.data['id'];
Convert Bean or Dio form your response like this or you can use this to convert JSON reponse to dart bean
import 'dart:convert';
Welcome welcomeFromJson(String str) {
final jsonData = json.decode(str);
return Welcome.fromJson(jsonData);
}
String welcomeToJson(Welcome data) {
final dyn = data.toJson();
return json.encode(dyn);
}
class Welcome {
int status;
List<Datum> data;
int totalRecord;
Welcome({
this.status,
this.data,
this.totalRecord,
});
factory Welcome.fromJson(Map<String, dynamic> json) => new Welcome(
status: json["status"] == null ? null : json["status"],
data: json["data"] == null ? null : new List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
totalRecord: json["totalRecord"] == null ? null : json["totalRecord"],
);
Map<String, dynamic> toJson() => {
"status": status == null ? null : status,
"data": data == null ? null : new List<dynamic>.from(data.map((x) => x.toJson())),
"totalRecord": totalRecord == null ? null : totalRecord,
};
}
class Datum {
String id;
String name;
String thumbnailUrl;
int plays;
String categories;
String categoriesIds;
String dataUrl;
int duration;
String createdAt;
int status;
int statusc;
int mediaType;
Datum({
this.id,
this.name,
this.thumbnailUrl,
this.plays,
this.categories,
this.categoriesIds,
this.dataUrl,
this.duration,
this.createdAt,
this.status,
this.statusc,
this.mediaType,
});
factory Datum.fromJson(Map<String, dynamic> json) => new Datum(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
thumbnailUrl: json["thumbnailUrl"] == null ? null : json["thumbnailUrl"],
plays: json["plays"] == null ? null : json["plays"],
categories: json["categories"] == null ? null : json["categories"],
categoriesIds: json["categoriesIds"] == null ? null : json["categoriesIds"],
dataUrl: json["dataUrl"] == null ? null : json["dataUrl"],
duration: json["duration"] == null ? null : json["duration"],
createdAt: json["createdAt"] == null ? null : json["createdAt"],
status: json["status"] == null ? null : json["status"],
statusc: json["statusc"] == null ? null : json["statusc"],
mediaType: json["mediaType"] == null ? null : json["mediaType"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null : name,
"thumbnailUrl": thumbnailUrl == null ? null : thumbnailUrl,
"plays": plays == null ? null : plays,
"categories": categories == null ? null : categories,
"categoriesIds": categoriesIds == null ? null : categoriesIds,
"dataUrl": dataUrl == null ? null : dataUrl,
"duration": duration == null ? null : duration,
"createdAt": createdAt == null ? null : createdAt,
"status": status == null ? null : status,
"statusc": statusc == null ? null : statusc,
"mediaType": mediaType == null ? null : mediaType,
};
}
This method returs you Reponse bean object
Future<Welcome> getMediaList() async {
String url='http://xxxxxx:xxx/onnet_api/mediaList.php';
http.Response res = await http.get(url);
final jsonData = json.decode(res.body);
var map=Map<String, dynamic>.from(jsonData);
var response=Welcome.fromJson(map);
if (res.statusCode == 200) {
return response;
} else {
throw Exception('Failed to load post');
}
}
Call this method like this
getMediaList().then((onValue){// on value is an object ot bean class //here you will be able to get members of your bean class })
and another way is to call your service is FutureBuilder<Welcome>();
You can add header and body in http.post Post url.
Future<UserResponse> loginService() async {
String qaurl = "https://www.xxxxxxxxx.com/api/loginapi.html";
var body = new Map<String, String>(); //here i defined Map ty
body['email'] =_email; // pe
body['password'] = _password;
body['return'] = 'json';
body['apikey'] = ApiKey;
http.Response res = await http.post(qaurl, body: body);
final jsonData = json.decode(res.body);
var map=Map<String, dynamic>.from(jsonData);
var loginResponse=UserResponse.fromJsonMap(map);
if (res.statusCode == 200) {
return loginResponse;
} else {
Navigator.of(context, rootNavigator: true).pop('dialog');
throw Exception('Failed to load post');
}
}
Related
I want to get only those item which contain type Lunch `` This is a function where I can fetch data from Rest Api and also ApiResponse added
I need to get specific data from a session I send instead of getting the entire array from the response from the Api() method. How do I capture just the only those item which contain type Lunch from the array?
{
"success": true,
"data": [
{
"id": 6,
"name": "Snack",
"type": "breakfast",
"detail": "18",
"image": "uploads/Screenshot_2022-12-04-13-15-13-27.jpg",
"carbs": 6,
"proteins": 4,
"fats": 8,
"cal": 4,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 7,
"name": "Chicken",
"type": "lunch",
"detail": "White Chicken",
"image": "uploads/1670258808164716637219.jpg",
"carbs": 15,
"proteins": 18,
"fats": 10,
"cal": 200,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 8,
"name": "546e57rufjvjv",
"type": "lunch",
"detail": "gdyhj",
"image": "uploads/meat.png",
"carbs": 6578,
"proteins": 2345,
"fats": 5678,
"cal": 4325,
"day": 5,
"created_at": null,
"updated_at": null
},
{
"id": 9,
"name": "Anda Tikki",
"type": "dinner",
"detail": "Egg and Daal",
"image": "uploads/1670259245043112842388.jpg",
"carbs": 10,
"proteins": 8,
"fats": 12,
"cal": 180,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 10,
"name": "Boiled egg and cucumber",
"type": "breakfast",
"detail": "Egg and cucumber",
"image": "uploads/1670259362662817976982.jpg",
"carbs": 10,
"proteins": 5,
"fats": 5,
"cal": 100,
"day": 2,
"created_at": null,
"updated_at": null
}
],
"message": "Food Data retrieved successfully."
}
Future<List<ProductsModel>> getProducts({String? query}) async {
List<ProductsModel> products = [];
var data=[];
try {
String url = 'https://diet.appetitor.app/Celo/api/user/food/2000.0';
var response = await Dio().get(url,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}));
if (response.statusCode == 200) {
products.clear();
ProductsModel.fromJson(response.data);
products.add(ProductsModel.fromJson(response.data));
if (query != null) {
print(products.length);
products = products
.map((e) {
e.data!.where((element) => element.type!.toLowerCase().contains('lunch'));
})
.cast<ProductsModel>()
.toList();
}
}
} on DioError catch (e) {
print(e.response);
}
return products;
}
}
If the response status code returns 200 after making a request with the rest api, assign the data in it to a variable of the type of your model, then you can get it from the variable as you want.
I'm new to oop and android dev and am trying to extract only a small part of this json file.I want to get back only the "heavyweight" rankings, no other weight division.. Any help would be highly appreciated!
Here is my model:
data class Rankings(
#SerializedName("rankings")
val rankings: List<Ranking>
)
data class Ranking(
#SerializedName("competitor_rankings")
val competitorRankings: List<CompetitorRanking>,
#SerializedName("name")
val name: String,
#SerializedName("type_id")
val typeId: Int,
#SerializedName("week")
val week: Int,
#SerializedName("year")
val year: Int
)
data class CompetitorRanking(
#SerializedName("competitor")
val competitor: Competitor,
#SerializedName("rank")
val rank: Int
)
data class Competitor(
#SerializedName("abbreviation")
val abbreviation: String,
#SerializedName("id")
val id: String,
#SerializedName("name")
val name: String
)
here is my api interface:
#GET("ufc/trial/v2/en/rankings.json")
suspend fun getRankings(#Query("api_key") api_key: String): Rankings
companion object {
fun create(): ApiInterface {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.sportradar.us/")
.addCallAdapterFactory(CoroutineCallAdapterFactory.invoke())
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(ApiInterface::class.java)
}
}
}
here's my api call:
lifecycleScope.launch(Dispatchers.IO) {
val result = api.getRankings("MY_API_KEY_WILL_GO_HERE")
Log.d(TAG,"${result.rankings}")
}
and here's my json file(I couldn't post the entire thing because of character limit, but it's essentially just 8 more rankings arrays):
"rankings": [
{
"type_id": 8,
"name": "pound_for_pound",
"year": 2020,
"week": 21,
"competitor_rankings": [
{
"rank": 1,
"movement": 0,
"competitor": {
"id": "sr:competitor:253371",
"name": "Jones, Jon",
"abbreviation": "JON"
}
},
{
"rank": 2,
"movement": 0,
"competitor": {
"id": "sr:competitor:250879",
"name": "Nurmagomedov, Khabib",
"abbreviation": "NUR"
}
},
{
"rank": 3,
"movement": 1,
"competitor": {
"id": "sr:competitor:237684",
"name": "Miocic, Stipe",
"abbreviation": "MIO"
}
},
{
"rank": 4,
"movement": 1,
"competitor": {
"id": "sr:competitor:410485",
"name": "Adesanya, Israel",
"abbreviation": "ADE"
}
},
{
"rank": 5,
"movement": 1,
"competitor": {
"id": "sr:competitor:253373",
"name": "Cormier, Daniel",
"abbreviation": "COR"
}
},
{
"rank": 6,
"movement": 1,
"competitor": {
"id": "sr:competitor:273539",
"name": "Usman, Kamaru",
"abbreviation": "USM"
}
},
{
"rank": 7,
"movement": 1,
"competitor": {
"id": "sr:competitor:290262",
"name": "Volkanovski, Alex",
"abbreviation": "VOL"
}
},
{
"rank": 8,
"movement": 1,
"competitor": {
"id": "sr:competitor:237676",
"name": "McGregor, Conor",
"abbreviation": "MCG"
}
},
{
"rank": 9,
"movement": 1,
"competitor": {
"id": "sr:competitor:237652",
"name": "Holloway, Max",
"abbreviation": "HOL"
}
},
{
"rank": 10,
"movement": 1,
"competitor": {
"id": "sr:competitor:351762",
"name": "Gaethje, Justin",
"abbreviation": "GAE"
}
},
{
"rank": 11,
"movement": 1,
"competitor": {
"id": "sr:competitor:261799",
"name": "Poirier, Dustin",
"abbreviation": "POI"
}
},
{
"rank": 12,
"movement": 1,
"competitor": {
"id": "sr:competitor:237646",
"name": "Ferguson, Tony",
"abbreviation": "FER"
}
},
{
"rank": 13,
"movement": 1,
"competitor": {
"id": "sr:competitor:253377",
"name": "Whittaker, Robert",
"abbreviation": "WHI"
}
},
{
"rank": 14,
"movement": 1,
"competitor": {
"id": "sr:competitor:274653",
"name": "Woodley, Tyron",
"abbreviation": "WOO"
}
},
{
"rank": 15,
"movement": 0,
"competitor": {
"id": "sr:competitor:250145",
"name": "Ngannou, Francis",
"abbreviation": "NGA"
}
}
]
},
{
"type_id": 16,
"name": "heavyweight",
"year": 2020,
"week": 21,
"competitor_rankings": [
{
"rank": 0,
"movement": 0,
"competitor": {
"id": "sr:competitor:237684",
"name": "Miocic, Stipe",
"abbreviation": "MIO"
}
},
{
"rank": 1,
"movement": 0,
"competitor": {
"id": "sr:competitor:253373",
"name": "Cormier, Daniel",
"abbreviation": "COR"
}
},
{
"rank": 2,
"movement": 0,
"competitor": {
"id": "sr:competitor:250145",
"name": "Ngannou, Francis",
"abbreviation": "NGA"
}
},
{
"rank": 3,
"movement": 0,
"competitor": {
"id": "sr:competitor:542009",
"name": "Blaydes, Curtis",
"abbreviation": "BLA"
}
},
{
"rank": 4,
"movement": 0,
"competitor": {
"id": "sr:competitor:237636",
"name": "Dos Santos, Junior",
"abbreviation": "DOS"
}
},
{
"rank": 4,
"movement": 1,
"competitor": {
"id": "sr:competitor:542099",
"name": "Lewis, Derrick",
"abbreviation": "LEW"
}
},
{
"rank": 6,
"movement": 0,
"competitor": {
"id": "sr:competitor:542143",
"name": "Rozenstruik, Jairzinho",
"abbreviation": "ROZ"
}
},
{
"rank": 7,
"movement": 0,
"competitor": {
"id": "sr:competitor:542161",
"name": "Volkov, Alexander",
"abbreviation": "VOL"
}
},
{
"rank": 8,
"movement": 0,
"competitor": {
"id": "sr:competitor:237694",
"name": "Overeem, Alistair",
"abbreviation": "OVE"
}
},
{
"rank": 9,
"movement": 0,
"competitor": {
"id": "sr:competitor:254231",
"name": "Harris, Walt",
"abbreviation": "HAR"
}
},
{
"rank": 10,
"movement": 0,
"competitor": {
"id": "sr:competitor:542117",
"name": "Oleinik, Aleksei",
"abbreviation": "OLE"
}
},
{
"rank": 11,
"movement": 0,
"competitor": {
"id": "sr:competitor:244080",
"name": "Abdurakhimov, Shamil",
"abbreviation": "ABD"
}
},
{
"rank": 12,
"movement": 0,
"competitor": {
"id": "sr:competitor:542079",
"name": "Ivanov, Blagoy",
"abbreviation": "IVA"
}
},
{
"rank": 13,
"movement": 0,
"competitor": {
"id": "sr:competitor:542145",
"name": "Sakai, Augusto",
"abbreviation": "SAK"
}
},
{
"rank": 14,
"movement": 0,
"competitor": {
"id": "sr:competitor:515358",
"name": "Pavlovich, Sergey",
"abbreviation": "PAV"
}
},
{
"rank": 15,
"movement": 0,
"competitor": {
"id": "sr:competitor:257349",
"name": "Werdum, Fabricio",
"abbreviation": "WER"
}
}
]
},
You can just use List.first method:
lifecycleScope.launch(Dispatchers.IO) {
val result = api.getRankings("MY_API_KEY_WILL_GO_HERE")
val ranking = result.rankings.first { it.name == "heavyweight" }
}
rankings.filter { it.name == "heavyweight" } will give you a list of heavyweight rankings. But it would be much better if your API had a way to filter those results on server side i.e. adding some filtering parameter to your request rather than getting all the results and filtering them on client side.
I'm making a project (for a programming class in uni) but when I try to run it in Android Studio, a warning appears very briefly in the emulator:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 5 column 21 path $[0].dateOfBirth
This is my JSON file:
{
"fighters": [
{
"id": 1,
"name": "Karl",
"dateOfBirth": "20-03-1975",
"level": 4,
"image": "karl.png"
},
{
"id": 2,
"name": "Geralt",
"dateOfBirth": "16-08-1964",
"level": 8,
"image": "Geralt.png"
},
{
"id": 3,
"name": "Darrak",
"dateOfBirth": "25-11-1940",
"level": 5,
"image": "Darrak.png"
},
{
"id": 4,
"name": "Jafar",
"dateOfBirth": "09-02-1920",
"level": 9,
"image": "Jafar.png"
},
{
"id": 5,
"name": "Cornelius",
"dateOfBirth": "28-06-1988",
"level": 2,
"image": "Cornelius.png"
},
{
"id": 6,
"name": "Laila",
"dateOfBirth": "18-10-1998",
"level": 5,
"image": "Laila.png"
},
{
"id": 7,
"name": "Marianne",
"dateOfBirth": "01-03-1975",
"level": 7,
"image": "Marianne.png"
},
{
"id": 8,
"name": "Petro",
"dateOfBirth": "10-07-1974",
"level": 10,
"image": "Petro.png"
},
{
"id": 9,
"name": "Ordelia",
"dateOfBirth": "18-05-1985",
"level": 5,
"image": "Ordelia.png"
},
{
"id": 10,
"name": "Lucina",
"dateOfBirth": "21-09-1992",
"level": 9,
"image": "Lucina.png"
},
{
"id": 11,
"name": "Hugo",
"dateOfBirth": "16-07-1938",
"level": 6,
"image": "Hugo.png"
},
{
"id": 12,
"name": "Sildar",
"dateOfBirth": "19-12-1980",
"level": 3,
"image": "Sildar.png"
},
{
"id": 13,
"name": "Zenok",
"dateOfBirth": "30-10-1999",
"level": 1,
"image": "Zenok.png"
},
{
"id": 14,
"name": "Violet",
"dateOfBirth": "02-04-2001",
"level": 8,
"image": "Violet.png"
},
{
"id": 15,
"name": "Tamara",
"dateOfBirth": "13-06-1963",
"level": 4,
"image": "Tamara.png"
}
],
"encounters": [
{
"id": 1,
"fighterId": 1,
"amount_of_monsters": 4,
"difficulty": "Medium"
},
{
"id": 2,
"fighterId": 5,
"amount_of_monsters": 1,
"difficulty": "Easy"
},
{
"id": 3,
"fighterId": 5,
"amount_of_monsters": 2,
"difficulty": "Medium"
},
{
"id": 4,
"fighterId": 7,
"amount_of_monsters": 1,
"difficulty": "Hard"
},
{
"id": 5,
"fighterId": 11,
"amount_of_monsters": 7,
"difficulty": "Medium"
},
{
"id": 6,
"fighterId": 7,
"amount_of_monsters": 2,
"difficulty": "Easy"
},
{
"id": 7,
"fighterId": 14,
"amount_of_monsters": 10,
"difficulty": "Extreme"
},
{
"id": 8,
"fighterId": 13,
"amount_of_monsters": 4,
"difficulty": "Medium"
},
{
"id": 9,
"fighterId": 7,
"amount_of_monsters": 5,
"difficulty": "Hard"
},
{
"id": 10,
"fighterId": 3,
"amount_of_monsters": 5,
"difficulty": "Easy"
}
]
}
Line 5 is "name": "Karl",
There's something wrong with my dateOfBirth attribute and I don't know why, because to me the syntax looks correct. I've tried reinstalling the app and rebuilding the project but that didn't work.
This is my first time posting a question on StackOverflow, so apologies if something isn't clear.
If anyone is able to help, I would greatly appreciate it.
EDIT (additional info)
I'm using Android Studio 3.6, API 29.
Android Gradle Plugin Version: 3.5.3
Gradle Version: 5.4.1
I use GSON to parse the JSON
JDK 11
This is the function I used for the GSON class:
fun getFighters(): Observable<Array<Fighter>> {
val observable = Observable.create<Array<Fighter>> { emitter ->
try {
var connection = connect("${BASE_URL}/fighters")
val gson = GsonBuilder().create()
val fighters = gson.fromJson(
InputStreamReader(connection.inputStream),
Array<Fighter>::class.java
)
for (fighter in fighters) {
connection = connect("${BASE_URL}/${fighter.image}")
fighter.imageBitmap = BitmapFactory.decodeStream(connection.inputStream)
}
emitter.onNext(fighters)
} catch(e: Exception) {
emitter.onError(e)
}
}
return observable
}
The BASE_URL is just a testing url since the assignment we have to do doesn't require to actually deploy the app. The for loop is to show the images of the Fighters in a RecyclerView list, so therefore I used a bitmap. Furthermore, here's the basic Fighter data class:
data class Fighter(
val id: Number,
val name: String,
val dateOfBirth: LocalDate,
val level: Number,
val image: String,
var imageBitmap: Bitmap
)
I think the class that you are using for parsing the JSON should be modified as follows.
data class Fighter(
val id: Number,
val name: String,
val dateOfBirth: String,
val level: Number,
val image: String,
var imageBitmap: Bitmap
)
The dateOfBirth is stored as a String in your JSON and you need to fetch that in that way. If you need to convert the value to a LocalDate object, you can always do that later after parsing the information. I hope that helps!
{
"count": 7,
"next": null,
"previous": null,
"results": [
{
"get_Infographs": [
{
"viewCount": 17,
"likecount": 1,
"unlikeCount": 1,
"shareCount": 0,
"i_id": 532,
"p_id": 532,
"name": "Yoga happiness educational s",
"description": "Yoga happiness educational spiritual journey lifestyle health ",
"c_id": 1,
"status_id": 1,
"source_id": 316,
"date_created": null,
"parentinfograph": "Language english grammar apo",
"internal_url": "http://167.99.86.81:8000/media/DQ532.png",
"external_url": "http://yogadork.com/wp-content/uploads/2015/01/2015-yoga-resolutions-infographic.png",
"mt_id": 3,
"mtcode": "Education",
"topics": [
{
"topic_code": "#EDUCATION"
},
{
"topic_code": "#HEALTH"
}
],
"geoPolitical": [
{
"gp_code": "Default / All GPIDs"
}
],
"entity": [],
"customMetaTags": [
{
"metatag": "#"
}
]
}
]
}
]
}
Read customMetaTags it as ArrayList and then you can pass it using bundle
bundle.putSerializable("some_string", arrayList)
I started working with sky-scanner API using volley on Android. I am able to poll the response from the API, however I have no clue how to parse the json which is sent in response, please see json below. The json response is very big, I have never worked with such responses before thus have no idea how can I handle this.
Can someone please help me figure this out? There is no sample implementation done by anyone for skyscanner for android.
JSON response to be parsed to get price, agents, flight number, carrier, duration of flight, image URL of flight.
{
"SessionKey": "97d1_ecilpojl_A",
"Query": {
"Country": "IN",
"Currency": "INR",
"Locale": "en-us",
"Adults": 1,
"Children": 0,
"Infants": 0,
"OriginPlace": "12627",
"DestinationPlace": "11712",
"OutboundDate": "2016-10-09",
"LocationSchema": "Default",
"CabinClass": "Economy",
"GroupPricing": false
},
"Status": "UpdatesComplete",
"Itineraries": [
{
"OutboundLegId": "12627-1610091100-AI-1-11712-1610091515",
"PricingOptions": [
{
"Agents": [
1963108
],
"QuoteAgeInMinutes": 5,
"Price": 19391.08,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fat24%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
2176206
],
"QuoteAgeInMinutes": 5,
"Price": 20190,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fcpin%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
4575202
],
"QuoteAgeInMinutes": 5,
"Price": 20315,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fyatr%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
4056270
],
"QuoteAgeInMinutes": 5,
"Price": 20457.92,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2ftpin%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
1943172
],
"QuoteAgeInMinutes": 5,
"Price": 20876,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fakbt%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
3987150
],
"QuoteAgeInMinutes": 5,
"Price": 20888.5,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2ft2in%2f1%2f12627.11712.2016-10-09%2fair%2ftrava%2fflights%3fitinerary%3dflight%7c-32672%7c446%7c12627%7c2016-10-09T11%3a00%7c10957%7c2016-10-09T12%3a35%3bflight%7c-"
},
{
"Agents": [
4035534
],
"QuoteAgeInMinutes": 5,
"Price": 20959.41,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2ftgin%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
1964238
],
"QuoteAgeInMinutes": 5,
"Price": 21207.92,
"DeeplinkUrl": "/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fatin%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
4060673
],
"QuoteAgeInMinutes": 5,
"Price": 21782,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2ftrea%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
3911604
],
"QuoteAgeInMinutes": 5,
"Price": 21782,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fsast%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
2391001
],
"QuoteAgeInMinutes": 5,
"Price": 21782,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http1.prod_0148f8394d6c2b79a407121f74dce6e1%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-10-02T12%3a09%3a13"
},
{
"Agents": [
4260937
],
"QuoteAgeInMinutes": 5,
"Price": 22217.64,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fviai%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
3929744
],
"QuoteAgeInMinutes": 5,
"Price": 22417.66,
"DeeplinkUrl": "deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http32672%26passengers%3d1%2c0%2c0%26channel%3ddataapi%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d22417.66%26is_npt%3dfalse%26is_multipart%3dfal
}
],
"BookingDetailsLink": {
"Uri": "/apiservices/pricing/v1.0/97d115d901944a33a4084a4a3170905f_ecilpojl_A1EA190098863E15CE039BCA9C3B1D16/booking",
"Body": "OutboundLegId=12627-1610091100-AI-1-11712-1610091515&InboundLegId=",
"Method": "PUT"
}
},
{
"OutboundLegId": "12627-1610090820-9W,AI-1-11712-1610091515",
"PricingOptions": [
{
"Agents": [
1963108
],
"QuoteAgeInMinutes": 5,
"Price": 37113.61,
"DeeplinkUrl": "/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fat24%2f1%2f12627.11712.2016-10-09%2fair%2ftrava%2fflights%3fitinerary%3dflight%7c-32177%7c2367%7c12627%7c2016-"
},
{
"Agents": [
2176206
],
"QuoteAgeInMinutes": 5,
"Price": 38374,
"DeeplinkUrl": "/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fcpin%2f1%2f12627.11712.2016-10-09%2fair%2ftrava%2fflights%3fitinerary%3dflight%7c-32177%7c2367%7c12627%7c2016-10-09T08%3a20%7c10957%7c2016-10-09T09%3a45%3bflight%7c-"
},
{
"Agents": [
4056270
],
"QuoteAgeInMinutes": 5,
"Price": 38854.31,
"DeeplinkUrl": "http://partners.api.skyscanner.net/apiservices/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2ftpin%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
1964238
],
"QuoteAgeInMinutes": 5,
"Price": 39604.31,
"DeeplinkUrl": "/deeplink/v2?_cje=9CRwSnJAYX4dZyvkLfQf7nyRn0MxGbhiKjD2KHvGPF9n99euZVUDq%2bzBrzQGTfTH&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fIN%2fen-us%2fINR%2fatin%2f1%2f12627.11712.2016-10-"
},
{
"Agents": [
2627411
],
"QuoteAgeInMinutes": 5,
"Price": 39932.95,
"DeeplinkUrl": "/deeplink/v2?_1.prod_8365f3bbc5ef11ab38406bb350796374%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-10-02T12%3a09%3a12"
},
{
"Agents": [
2042574
],
"QuoteAgeInMinutes": 5,
"Price": 43940.34,
"DeeplinkUrl": "/deeplink/v2?32672%26passengers%3d1%2c0%2c0%26channel%3ddataapi%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d43940.34%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3dskyscanner_b2b%26request_id%3dd4cc5531-1a4b-4c76-a063-447e7a8baeea%26deeplink_ids%3dap-northeast-1.prod_0b228b45aaf97f3276f40ee4109e8faf%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-10-02T12%3a09%3a13"
}
],
"BookingDetailsLink": {
"Uri": "/apiservices/pricing/v1.0/97d115d901944a33a4084a4a3170905f_ecilpojl_A1EA190098863E15CE039BCA9C3B1D16/booking",
"Body": "OutboundLegId=12627-1610090820-9W,AI-1-11712-1610091515&InboundLegId=",
"Method": "PUT"
}
}
],
"Legs": [
{
"Id": "12627-1610091100-AI-1-11712-1610091515",
"SegmentIds": [
1,
2
],
"OriginStation": 12627,
"DestinationStation": 11712,
"Departure": "2016-10-09T11:00:00",
"Arrival": "2016-10-09T15:15:00",
"Duration": 255,
"JourneyMode": "Flight",
"Stops": [
10957
],
"Carriers": [
841
],
"OperatingCarriers": [
841
],
"Directionality": "Outbound",
"FlightNumbers": [
{
"FlightNumber": "446",
"CarrierId": 841
},
{
"FlightNumber": "433",
"CarrierId": 841
}
]
},
{
"Id": "12627-1610090820-9W,AI-1-11712-1610091515",
"SegmentIds": [
3,
2
],
"OriginStation": 12627,
"DestinationStation": 11712,
"Departure": "2016-10-09T08:20:00",
"Arrival": "2016-10-09T15:15:00",
"Duration": 415,
"JourneyMode": "Flight",
"Stops": [
10957
],
"Carriers": [
471,
841
],
"OperatingCarriers": [
471,
841
],
"Directionality": "Outbound",
"FlightNumbers": [
{
"FlightNumber": "433",
"CarrierId": 841
},
{
"FlightNumber": "2367",
"CarrierId": 471
}
]
}
],
"Segments": [
{
"Id": 1,
"OriginStation": 12627,
"DestinationStation": 10957,
"DepartureDateTime": "2016-10-09T11:00:00",
"ArrivalDateTime": "2016-10-09T12:35:00",
"Carrier": 841,
"OperatingCarrier": 841,
"Duration": 95,
"FlightNumber": "446",
"JourneyMode": "Flight",
"Directionality": "Outbound"
},
{
"Id": 2,
"OriginStation": 10957,
"DestinationStation": 11712,
"DepartureDateTime": "2016-10-09T13:40:00",
"ArrivalDateTime": "2016-10-09T15:15:00",
"Carrier": 841,
"OperatingCarrier": 841,
"Duration": 95,
"FlightNumber": "433",
"JourneyMode": "Flight",
"Directionality": "Outbound"
},
{
"Id": 3,
"OriginStation": 12627,
"DestinationStation": 10957,
"DepartureDateTime": "2016-10-09T08:20:00",
"ArrivalDateTime": "2016-10-09T09:45:00",
"Carrier": 471,
"OperatingCarrier": 471,
"Duration": 85,
"FlightNumber": "2367",
"JourneyMode": "Flight",
"Directionality": "Outbound"
}
],
"Carriers": [
{
"Id": 841,
"Code": "AI",
"Name": "Air India",
"ImageUrl": "http://s1.apideeplink.com/images/airlines/AI.png",
"DisplayCode": "AI"
},
{
"Id": 471,
"Code": "9W",
"Name": "Jet Airways",
"ImageUrl": "http://s1.apideeplink.com/images/airlines/9W.png",
"DisplayCode": "9W"
}
],
"Agents": [
{
"Id": 1963108,
"Name": "Mytrip",
"ImageUrl": "http://s1.apideeplink.com/images/websites/at24.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"BookingNumber": "+448447747881",
"Type": "TravelAgent"
},
{
"Id": 2176206,
"Name": "Cheapticket.in",
"ImageUrl": "http://s1.apideeplink.com/images/websites/cpin.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 4575202,
"Name": "Yatra.com",
"ImageUrl": "http://s1.apideeplink.com/images/websites/yatr.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"BookingNumber": "18001029900",
"Type": "TravelAgent"
},
{
"Id": 4056270,
"Name": "Tripsta",
"ImageUrl": "http://s1.apideeplink.com/images/websites/tpin.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 1943172,
"Name": "AkbarTravels.com",
"ImageUrl": "http://s1.apideeplink.com/images/websites/akbt.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 3987150,
"Name": "Travel2be",
"ImageUrl": "http://s1.apideeplink.com/images/websites/t2in.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 4035534,
"Name": "Travelgenio",
"ImageUrl": "http://s1.apideeplink.com/images/websites/tgin.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 1964238,
"Name": "airtickets",
"ImageUrl": "http://s1.apideeplink.com/images/websites/atin.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 4060673,
"Name": "Traveasy.co.in",
"ImageUrl": "http://s1.apideeplink.com/images/websites/trea.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 3911604,
"Name": "Sastiticket.com",
"ImageUrl": "http://s1.apideeplink.com/images/websites/sast.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 2391001,
"Name": "EaseMyTrip.com",
"ImageUrl": "http://s1.apideeplink.com/images/websites/emti.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 4260937,
"Name": "via.com",
"ImageUrl": "http://s1.apideeplink.com/images/websites/viai.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 3929744,
"Name": "Simplio",
"ImageUrl": "http://s1.apideeplink.com/images/websites/simp.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 2627411,
"Name": "GotoGate",
"ImageUrl": "http://s1.apideeplink.com/images/websites/gtas.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 2042574,
"Name": "Bravofly",
"ImageUrl": "http://s1.apideeplink.com/images/websites/bfin.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 1882712,
"Name": "ebookers",
"ImageUrl": "http://s1.apideeplink.com/images/websites/a178.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": true,
"Type": "TravelAgent"
},
{
"Id": 4366985,
"Name": "Wegoby.com",
"ImageUrl": "http://s1.apideeplink.com/images/websites/wgby.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 3291237,
"Name": "My Travel Genie",
"ImageUrl": "http://s1.apideeplink.com/images/websites/mtge.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 3588558,
"Name": "Tripair",
"ImageUrl": "http://s1.apideeplink.com/images/websites/pein.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"Type": "TravelAgent"
},
{
"Id": 2834897,
"Name": "Air India",
"ImageUrl": "http://s1.apideeplink.com/images/websites/inda.png",
"Status": "UpdatesComplete",
"OptimisedForMobile": false,
"BookingNumber": "18001801407",
"Type": "Airline"
}
],
"Places": [
{
"Id": 12627,
"ParentId": 3462,
"Code": "IXL",
"Type": "Airport",
"Name": "Leh"
},
{
"Id": 10957,
"ParentId": 3401,
"Code": "DEL",
"Type": "Airport",
"Name": "New Delhi"
},
{
"Id": 11712,
"ParentId": 3424,
"Code": "GAY",
"Type": "Airport",
"Name": "Gaya"
},
{
"Id": 3462,
"ParentId": 170,
"Code": "IXL",
"Type": "City",
"Name": "Leh"
},
{
"Id": 3401,
"ParentId": 170,
"Code": "DEL",
"Type": "City",
"Name": "New Delhi"
},
{
"Id": 3424,
"ParentId": 170,
"Code": "GAY",
"Type": "City",
"Name": "Gaya"
},
{
"Id": 170,
"Code": "IN",
"Type": "Country",
"Name": "India"
}
],
"Currencies": [
{
"Code": "INR",
"Symbol": "₹",
"ThousandsSeparator": ",",
"DecimalSeparator": ".",
"SymbolOnLeft": true,
"SpaceBetweenAmountAndSymbol": false,
"RoundingCoefficient": 0,
"DecimalDigits": 2
}
]
}
If you are able to pull the json data then try using this js script:
Make sure to add jQuery
Change the value of the url variable with the session poll url you created
NOTE: Please take note that you will encounter cross origin error when you try to run this script here.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
( function( window, document, $ ){
var app = {};
app.init = function()
{
app.flightsGeo();
};
app.flightsGeo = function( )
{
// the session poll url you created
var url = 'http://business.skyscanner.net/apiservices/pricing/hk1/v1.0/<sessionKey>?apikey=<apikey>';
$.ajax({
type: "GET",
url: url,
dataType: 'json',
success: function( response ){
var itineraries = response.Itineraries;
var agents = response.Agents;
var legs = response.Legs;
var carriers = response.Carriers;
var places = response.Places;
$.each(itineraries, function( itineraryKey, itineraryVal ){
var inbound = app.getObjects( legs, 'Id', itineraryVal.InboundLegId),
inDepartureTime = inbound[0].Departure,
inArrivalTime = inbound[0].Arrival,
inDepartureDate = inbound[0].Departure,
inArrivalDate = inbound[0].Arrival,
inOrigin = app.getObjects( places, 'Id', inbound[0].DestinationStation),
inDestination = app.getObjects( places, 'Id', inbound[0].OriginStation),
inCarriers = app.getObjects( carriers, 'Id', inbound[0].OperatingCarriers[0]);
var outbound = app.getObjects( legs, 'Id', itineraryVal.OutboundLegId),
outDepartureTime = outbound[0].Departure,
outArrivalTime = outbound[0].Arrival,
outDepartureDate = outbound[0].Departure,
outArrivalDate = outbound[0].Arrival,
outOrigin = app.getObjects( places, 'Id', outbound[0].DestinationStation),
outDestination = app.getObjects( places, 'Id', outbound[0].OriginStation),
outCarriers = app.getObjects( carriers, 'Id', outbound[0].OperatingCarriers[0]);
var agent = app.getObjects( agents, 'Id', itineraryVal.PricingOptions[0].Agents[0]);
var price = itineraryVal.PricingOptions[0].Price.toFixed(2);
var permalink = itineraryVal.PricingOptions[0].DeeplinkUrl;
var time = itineraryVal.PricingOptions[0].QuoteAgeInMinutes;
// NEW FORMAT OF DATA
var data = {
agent : agent,
price : price,
time : time,
permalink : permalink,
inbound : {
time : {
departure : inDepartureTime,
arrival : inArrivalTime
},
date : {
departure : inDepartureDate,
arrival : inArrivalDate
},
station : {
origin : inOrigin,
destination : inDestination
},
carriers : inCarriers
},
outbound : {
time : {
departure : outDepartureTime,
arrival : outArrivalTime
},
date : {
departure : outDepartureDate,
arrival : outArrivalDate
},
station : {
origin : outOrigin,
destination : outDestination
},
carriers : outCarriers
}
};
// will display the NEW FORMAT OF DATA
console.log( data );
});
},
error: function( error ){
console.log( error );
}
});
};
app.displayData = function( data )
{
console.log( data );
};
app.getObjects = function(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(app.getObjects(obj[i], key, val));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(obj);
}
}
}
return objects;
};
$(document).ready( app.init );
return app;
})( window, document, jQuery );
</script>
P.S. I hope this will helps you the idea how to get the data you need.
I'll show a basic example of how to parse. Take the following sample JSON.
http://api.androidhive.info/contacts/
How to get the contacts list.
JSONObject jsonObj = new JSONObject("Your JSON String here");
JSONArray contacts = jsonObj.optJSONArray("contacts");
How to calculate the phone number
//Get first contact
JSONObject firstContact = contacts.optJSONObject(0);
JSONObject phone = firstContact.optJSONObject("phone");
String mobileNo = phone.optString("mobile");
Similarly you can apply this technique to your JSON.