Related
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!
{
"totalHits": 500,
"hits": [
{
"largeImageURL": "https://pixabay.com/get/52e3d6414352af14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_1280.jpg",
"webformatHeight": 424,
"webformatWidth": 640,
"likes": 11,
"imageWidth": 4456,
"id": 4332903,
"user_id": 1151065,
"views": 697,
"comments": 14,
"pageURL": "https://pixabay.com/photos/evangelion-mech-unit-02-robot-4332903/",
"imageHeight": 2958,
"webformatURL": "https://pixabay.com/get/52e3d6414352af14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "evangelion mech unit 02, robot, fighter",
"downloads": 311,
"user": "vinsky2002",
"favorites": 0,
"imageSize": 878944,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2019/05/15/02-40-06-911_250x250.png",
"previewURL": "https://cdn.pixabay.com/photo/2019/07/12/13/44/evangelion-mech-unit-02-4332903_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/55e7d54b4d51a514f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_1280.jpg",
"webformatHeight": 359,
"webformatWidth": 640,
"likes": 18,
"imageWidth": 3863,
"id": 3708739,
"user_id": 10248012,
"views": 2696,
"comments": 2,
"pageURL": "https://pixabay.com/photos/sky-dark-night-moon-moonlight-3708739/",
"imageHeight": 2170,
"webformatURL": "https://pixabay.com/get/55e7d54b4d51a514f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "sky, dark, night",
"downloads": 1036,
"user": "Sritam_kumar_Sethy",
"favorites": 25,
"imageSize": 2027189,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2019/09/28/19-27-53-806_250x250.jpeg",
"previewURL": "https://cdn.pixabay.com/photo/2018/09/28/08/37/sky-3708739_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/57e2dc4a4c5aaf14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_1280.jpg",
"webformatHeight": 360,
"webformatWidth": 640,
"likes": 14,
"imageWidth": 4608,
"id": 1299683,
"user_id": 1151065,
"views": 2932,
"comments": 3,
"pageURL": "https://pixabay.com/photos/panda-z-panda-toy-children-child-1299683/",
"imageHeight": 2592,
"webformatURL": "https://pixabay.com/get/57e2dc4a4c5aaf14f6da8c7dda79367b153fdee254506c4870277bd3934ec45ebf_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "panda-z, panda, toy",
"downloads": 1067,
"user": "vinsky2002",
"favorites": 7,
"imageSize": 1745060,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2019/05/15/02-40-06-911_250x250.png",
"previewURL": "https://cdn.pixabay.com/photo/2016/04/01/09/56/panda-z-1299683_150.jpg"
},
],
"total": 588
}
The API I'm fetching returns json value like this. I wrote the following code to extract the data, it works if I code it like this and the widget builds, but with this error before the widget loads
Future getJsonData() async{
var response;
for(int i=1; i<=5; i++){
response = await http.get(
Uri.encodeFull(widget.api+i.toString()),
headers: {"Accept": "application/json"}
);
setState(() {
var toJsonData = json.decode(response.body);
item.addAll(toJsonData['hits']);
});
}
print(response.body);
return item;
}
error image
But when I use FutureBuilder method, it fails to create the widget. It would be helpful if someone can tell a possibly working FutureBuilder method for this json data.
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');
}
}
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.
I have a json response that looks somewhat like this.
{
"id": 1,
"username": "user",
"email": "generic user#gmail.com",
"name": "harshvardhan",
"phone_no": 2147483647,
"created_at": "2016-06-27 12:23:25",
"updated_at": "2016-06-27 12:23:25",
"hash": "",
"groups": [
{
"id": 37,
"title": "aspernatur-et-rem-quos-eius-voluptatem-eveniet-aut",
"descr": "33",
"identifier": "5771545383a2d",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:07",
"pivot": {
"user_id": 1,
"grp_id": 37,
"roles": "admin"
}
},
{
"id": 67,
"title": "quibusdam-voluptas-non-facere-nihil",
"descr": "194",
"identifier": "57715453b8d80",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:07",
"pivot": {
"user_id": 1,
"grp_id": 67,
"roles": "admin"
}
},
{
"id": 161,
"title": "libero-id-ipsa-beatae-aut",
"descr": "59",
"identifier": "5771545469db4",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:08",
"pivot": {
"user_id": 1,
"grp_id": 161,
"roles": "admin"
}
},
{
"id": 198,
"title": "iure-ad-sunt-id-delectus-laboriosam-quo",
"descr": "150",
"identifier": "57715454a9d15",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:08",
"pivot": {
"user_id": 1,
"grp_id": 198,
"roles": "admin"
}
}
]
}
There is a many to many relationship between users and groups.
I am using retrofit with the GsonConverterFactory. On response, how can I parse this information into objects?
I tried making a User class , and a group class, then I put an array of groups as a member of the user class.
But when I access User.getGroups().get(1).getID , it returns 0.
However, User.getGroups().size() does return 4 (the correct number in this case)
How can I achieve this in retrofit?
A practical tool to parse JSON correctly with retrofit can be to generate the classes with http://www.jsonschema2pojo.org
You just have to put the example JSON, the resource type in JSON and put the desired annotation style (GSON, Jackson, ..).
Finally click on the preview button and you can see the results