Gson get a json variable in the class - java

I am making a weather app to understand how to use Gson and web api's with java here is my current code:
public class Weather
{
public static void main(String[] args) throws Exception
{
URL ipStacks = new URL("http://api.ipstack.com/check?access_key=(my api key)");
BufferedReader reader = new BufferedReader(
new InputStreamReader(ipStacks.openStream()));
String inputLine = reader.readLine();
String json = inputLine;
Gson gson = new Gson();
LocationData location = gson.fromJson(json, LocationData.class);
System.out.println(location.ip);
System.out.println(location.latitude);
System.out.println(location.longitude);
String darkSkyBase = "https://api.darksky.net/forecast/(my api key)/";
URL darkSky = new URL(darkSkyBase+location.latitude+","+location.longitude);
BufferedReader reader2 = new BufferedReader(
new InputStreamReader(darkSky.openStream()));
inputLine = reader2.readLine();
WeatherData weather = gson.fromJson(inputLine, WeatherData.class);
System.out.println(weather.currently);
}
}
class LocationData
{
String ip;
String latitude;
String longitude;
}
class WeatherData
{
String currently;
}
I am getting this error:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 81 path $.currently
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:927)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.thomasbriggs.json.App.main(App.java:37)
Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 81 path $.currently
at com.google.gson.stream.JsonReader.nextString(JsonReader.java:825)
at com.google.gson.internal.bind.TypeAdapters$16.read(TypeAdapters.java:402)
at com.google.gson.internal.bind.TypeAdapters$16.read(TypeAdapters.java:390)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
... 5 more
I am guessing because with the darksky api the currently is another json list but how do I tell Gson to expect a json list?
The JSON string I am having trouble with looks like this:
{
"latitude": 42.3601,
"longitude": -71.0589,
"timezone": "America/New_York",
"currently": {
"time": 1509993277,
"summary": "Drizzle",
"icon": "rain",
"nearestStormDistance": 0,
"precipIntensity": 0.0089,
"precipIntensityError": 0.0046,
"precipProbability": 0.9,
"precipType": "rain",
"temperature": 66.1,
"apparentTemperature": 66.31,
"dewPoint": 60.77,
"humidity": 0.83,
"pressure": 1010.34,
"windSpeed": 5.59,
"windGust": 12.03,
"windBearing": 246,
"cloudCover": 0.7,
"uvIndex": 1,
"visibility": 9.84,
"ozone": 267.44
},
"minutely": {
"summary": "Light rain stopping in 13 min., starting again 30 min. later.",
"icon": "rain",
"data": [{
"time": 1509993240,
"precipIntensity": 0.007,
"precipIntensityError": 0.004,
"precipProbability": 0.84,
"precipType": "rain"
},
...
]
},
"hourly": {
"summary": "Rain starting later this afternoon, continuing until this evening.",
"icon": "rain",
"data": [{
"time": 1509991200,
"summary": "Mostly Cloudy",
"icon": "partly-cloudy-day",
"precipIntensity": 0.0007,
"precipProbability": 0.1,
"precipType": "rain",
"temperature": 65.76,
"apparentTemperature": 66.01,
"dewPoint": 60.99,
"humidity": 0.85,
"pressure": 1010.57,
"windSpeed": 4.23,
"windGust": 9.52,
"windBearing": 230,
"cloudCover": 0.62,
"uvIndex": 1,
"visibility": 9.32,
"ozone": 268.95
},
...
]
},
"daily": {
"summary": "Mixed precipitation throughout the week, with temperatures falling to 39°F on Saturday.",
"icon": "rain",
"data": [{
"time": 1509944400,
"summary": "Rain starting in the afternoon, continuing until evening.",
"icon": "rain",
"sunriseTime": 1509967519,
"sunsetTime": 1510003982,
"moonPhase": 0.59,
"precipIntensity": 0.0088,
"precipIntensityMax": 0.0725,
"precipIntensityMaxTime": 1510002000,
"precipProbability": 0.73,
"precipType": "rain",
"temperatureHigh": 66.35,
"temperatureHighTime": 1509994800,
"temperatureLow": 41.28,
"temperatureLowTime": 1510056000,
"apparentTemperatureHigh": 66.53,
"apparentTemperatureHighTime": 1509994800,
"apparentTemperatureLow": 35.74,
"apparentTemperatureLowTime": 1510056000,
"dewPoint": 57.66,
"humidity": 0.86,
"pressure": 1012.93,
"windSpeed": 3.22,
"windGust": 26.32,
"windGustTime": 1510023600,
"windBearing": 270,
"cloudCover": 0.8,
"uvIndex": 2,
"uvIndexTime": 1509987600,
"visibility": 10,
"ozone": 269.45,
"temperatureMin": 52.08,
"temperatureMinTime": 1510027200,
"temperatureMax": 66.35,
"temperatureMaxTime": 1509994800,
"apparentTemperatureMin": 52.08,
"apparentTemperatureMinTime": 1510027200,
"apparentTemperatureMax": 66.53,
"apparentTemperatureMaxTime": 1509994800
},
...
]
},
"alerts": [
{
"title": "Flood Watch for Mason, WA",
"time": 1509993360,
"expires": 1510036680,
"description": "...FLOOD WATCH REMAINS IN EFFECT THROUGH LATE MONDAY NIGHT...\nTHE FLOOD WATCH CONTINUES FOR\n* A PORTION OF NORTHWEST WASHINGTON...INCLUDING THE FOLLOWING\nCOUNTY...MASON.\n* THROUGH LATE FRIDAY NIGHT\n* A STRONG WARM FRONT WILL BRING HEAVY RAIN TO THE OLYMPICS\nTONIGHT THROUGH THURSDAY NIGHT. THE HEAVY RAIN WILL PUSH THE\nSKOKOMISH RIVER ABOVE FLOOD STAGE TODAY...AND MAJOR FLOODING IS\nPOSSIBLE.\n* A FLOOD WARNING IS IN EFFECT FOR THE SKOKOMISH RIVER. THE FLOOD\nWATCH REMAINS IN EFFECT FOR MASON COUNTY FOR THE POSSIBILITY OF\nAREAL FLOODING ASSOCIATED WITH A MAJOR FLOOD.\n",
"uri": "http://alerts.weather.gov/cap/wwacapget.php?x=WA1255E4DB8494.FloodWatch.1255E4DCE35CWA.SEWFFASEW.38e78ec64613478bb70fc6ed9c87f6e6"
},
...
],
{
"flags": {
"units": "us",
...
}
}
Any help would be great, if you have any question please ask.

currently is a object while your type is String. If you do not want to create structure for currently then declare it as a map Map<String, Object> currently - GSON will put all key-value pairs here

I was checking the JSON and it seems your are getting double values for longitude and latitude:
"latitude": 42.3601,
"longitude": -71.0589,
but you are trying to save them in String
class LocationData
{
String ip;
String latitude;
String longitude;
}
Change the variables to double and try again.

Related

Exception in thread "AWT-EventQueue-0" javax.json.stream.JsonParsingException: Unexpected char 100 at (line no=1, column no=2, offset=1

I have a json file which I got from my backend.
The json file is as follows.
{
"documentTemplate": {
"pageFormat": {
"pageWidth": "50",
"pageLength": "13",
"usePageLengthFromPrinter": false
},
"template": {
"header": [
" Delivery Order ",
"Date : ${date} NO. : ${no_surat} ",
"Customer: ${customer} Delivery Date: ${delivery_date}"
],
"detail": [
{
"table": "table_details",
"border": "true",
"columns": [
{
"source": "description",
"width": 9,
"caption": "DESCRIPTION"
},
{
"source": "do_hanwa_and_date",
"width": 9,
"caption": "DO HW / DATE HW"
},
{
"source": "qty",
"width": 9,
"caption": "QTY"
},
{
"source": "nett",
"width": 9,
"caption": "NETT"
},
{
"source": "gross",
"width": 9,
"caption": "GROSS"
},
{
"source": "size",
"width": 9,
"caption": "SIZE"
},
{
"source": "location",
"width": 9,
"caption": "LOCATION"
},
{
"source": "urut",
"width": 9,
"caption": "URUT"
}
]
},
" ",
" ",
" ___________ ___________ ",
" (Signature) (Signature) "
]
}
},
"documentValue": {
"date": "13-05-2019",
"no_surat": "01024/05/DO-MARU/19JKT",
"customer": "PT. WIJAYA STEELINDO",
"delivery_date": "13-05-2019",
"table_details": [
{
"description": "03NKBTL190205005/12",
"do_hanwa_and_date": "46916 / 29-03-2019",
"qty": "1",
"nett": "4,568",
"gross": "4,616",
"size": "0.70MM X 151.8MM",
"location": "PT2212",
"urut": 64592
},
{
"description": "03NKBTL190204997/04",
"do_hanwa_and_date": "46916 / 29-03-2019",
"qty": "1",
"nett": "4,504",
"gross": "4,552",
"size": "0.70MM X 151.8MM",
"location": "PU5111",
"urut": 64591
}
]
}
}
To process the data: I use Gson.
public class Report {
String filePathString;
public HashMap<String, String> convertJsonToObject() {
Gson gson = new Gson();
try (JsonReader reader = new JsonReader(new FileReader(this.filePathString) )) {
// Converting JSON File to Java Object
HashMap<String, String> hashMapResult = gson.fromJson(reader, HashMap.class);
return hashMapResult;
} catch (IOException e) {
}
return null;
}
It's time to use the data from the GSON converter.
I use JSwing.
private void jButtonCompileGsonActionPerformed(java.awt.event.ActionEvent evt) {
// Create a report, param => file`s path
Report report = new Report(jTextFieldPathFile.getText());
// Read the file, as the return is a hashMap
HashMap<String, String> result = report.convertJsonToObject();
// Get based key
String documentTemplate = String.valueOf(result.get("documentTemplate")).replaceAll("\r?\n", "");
String documentValue = String.valueOf(result.get("documentValue")).replaceAll("\r?\n", "");
// Just to clarify
System.out.println(documentTemplate);
System.out.println(documentValue);
}
The result is:
documentTemplate => {pageFormat={pageWidth=50, pageLength=13, usePageLengthFromPrinter=false}, template={header=[ Delivery Order , Date : ${date} NO. : ${no_surat} , Customer: ${customer} Delivery Date: ${delivery_date}], detail=[{table=table_details, border=true, columns=[{source=description, width=9.0, caption=DESCRIPTION}, {source=do_hanwa_and_date, width=9.0, caption=DO HW / DATE HW}, {source=qty, width=9.0, caption=QTY}, {source=nett, width=9.0, caption=NETT}, {source=gross, width=9.0, caption=GROSS}, {source=size, width=9.0, caption=SIZE}, {source=location, width=9.0, caption=LOCATION}, {source=urut, width=9.0, caption=URUT}]}, , , ___________ ___________ , (Signature) (Signature) ]}}
documentValue => {date=13-05-2019, no_surat=01024/05/DO-MARU/19JKT, customer=PT. WIJAYA STEELINDO, delivery_date=13-05-2019, table_details=[{description=03NKBTL190205005/12, do_hanwa_and_date=46916 / 29-03-2019, qty=1, nett=4,568, gross=4,616, size=0.70MM X 151.8MM, location=PT2212, urut=64592.0}, {description=03NKBTL190204997/04, do_hanwa_and_date=46916 / 29-03-2019, qty=1, nett=4,504, gross=4,552, size=0.70MM X 151.8MM, location=PU5111, urut=64591.0}]}
I use this library: SimpleESCP
From these libraries, the interpretation is as follows.
import javax.json.JsonObject;
public class JsonDataSource implements DataSource {
private static final Logger LOG;
private JsonObject source;
public JsonDataSource(String jsonString){
}
}
I use it like this and get the following error message:
JsonDataSource jsonDataSource = new JsonDataSource(documentValue);
Exception in thread "AWT-EventQueue-0" javax.json.stream.JsonParsingException: Unexpected char 100 at (line no=1, column no=2, offset=1)
Please help and advice.
Thank you.

How to convert JSON Response to String Array

This is the JSON Response I received from OpenWeatherMap:
{
"coord": {
"lon": 85.84,
"lat": 20.26
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 305.15,
"pressure": 1007,
"humidity": 70,
"temp_min": 305.15,
"temp_max": 305.15
},
"visibility": 5000,
"wind": {
"speed": 4.1,
"deg": 170
},
"clouds": {
"all": 20
},
"dt": 1551686400,
"sys": {
"type": 1,
"id": 9113,
"message": 0.0037,
"country": "IN",
"sunrise": 1551659668,
"sunset": 1551702153
},
"id": 1275817,
"name": "Bhubaneswar",
"cod": 200
}
While I am able to use Weather by using this code below but unable to convert main to array. Is there anyway I can convert the bolded response to array or String.
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for(int i=0;i<arr.length();i++)
{
JSONObject jsonPart = arr.getJSONObject(i);
String main = jsonPart.getString("main");
String description =jsonPart.getString("description");
if(main !="" && description !="")
{
message += main + " : " + description + "\r\n";
}
}
The suggestion is, don't parse the JSON by hand. Use third party library like Gson to parse the JSON. This way you won't run into any typo errors and let the library handle the parsing for you.
Paste your json string to this website, and generate your pojo. Use the Gson to parse your string and bind to generated pojo.

How to convert the tree structured json to Java object using gson

[
{
"sentence": "I want to buy shoes .",
"tree": {
"ROOT": [
{
"index": 2,
"token": "want",
"label": "VERB",
"pos": "VBP",
"tree": {
"nsubj": [
{
"index": 1,
"token": "I",
"label": "PRON",
"pos": "PRP"
}
],
"xcomp": [
{
"index": 4,
"token": "buy",
"label": "VERB",
"pos": "VB",
"tree": {
"aux": [
{
"index": 3,
"token": "to",
"label": "PRT",
"pos": "TO"
}
],
"dobj": [
{
"index": 5,
"token": "shoes",
"label": "NOUN",
"pos": "NNS"
}
]
}
}
],
"punct": [
{
"index": 6,
"token": ".",
"label": ".",
"pos": "."
}
]
}
}
]
}
}
]
This is tree represented in Json. But the keys for nested nodes keep changing.
For example "ROOT, nsubj, xcomp" ... etc.
How do I convert above json code to Java Object using gson.
Above response is from syntaxnet Parsey_Mcparseface api I'm trying to use.
Thanks in advance.
Gson has a method Gson#fromJson. For example, this is a code to read a simple String object.
Gson gson = new Gson();
String str = gson.fromJson("\"hello\"", String.class);
System.out.println("String: " + str);
You need to prepare Java Object to read your proposed JSON. But, you don't need to write code by yourself. There is a website providing automatical JSON object generator.
jsonschema2pojo
enter following items:
Target language: Java
Source type: JSON
Annotation type: Gson
and enter your class name, for example "ParsedSentence"
then, write code. You will get object.
Gson gson = new Gson();
ParsedSentence parsed = gson.fromJson(longLongJsonString, ParsedSentence.class);

How to get specific bits of json response effectively?

Im requesting data from instagram api when I search for any tag. In return I get a massive chunk of json data corresponding to like 20 pictures. The response below is the chunk I used to generate my pojos online
{
"pagination": {
"next_max_tag_id": "1193052000552992097",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1193052000552992097",
"next_min_id": "1193052554319844057",
"min_tag_id": "1193052554319844057",
"next_url": "https://api.instagram.com/v1/tags/cats/media/recent?access_token=631477962.1fb234f.f7c5cda97c7f4df983b1c764f066ed37&max_tag_id=1193052000552992097"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"cats",
"caseworker",
"homestuck"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1456442969",
"link": "https://www.instagram.com/p/BCOkvoim1LZ/",
"likes": {
"count": 0,
"data": []
},
"images": {
"low_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 320,
"height": 320
},
"thumbnail": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1456442969",
"text": "Bitch! I'm fabulous! That's my case worker..she is obsessed with cats\n\n#cats #caseworker #homestuck",
"from": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
},
"id": "1193052563471815092"
},
"user_has_liked": false,
"id": "1193052554319844057_2322171747",
"user": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
}
}
So when I do that I get like 10-12 different pojo classes into which I should map this data. Now firstly...Im just trying that out and Im 100% Ill have some problem mapping them I mean gson will do it for me but i dont know if there are any more that I would need etc.
but most importantly my app only needs the low standard url pictures all the other information is useless for me.
Ofcourse, I know one way to do it which is to convert the whole thing into a string and parse the whole string through multiple times looking for key words etc and making images etc. I dont want to do that because its ugly. It works but I want a concise way of doing that at the same time without mapping completely.
Using Gson's JsonParser class, you can parse your JSON into a tree of JsonElements, and then extract just the data that you need.
For example, in order to print out all the low resolution URLs, you could use the following code:
String json = "...";
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(json).getAsJsonObject();
JsonArray data = object.getAsJsonArray("data");
for (JsonElement element : data) {
JsonObject images = element.getAsJsonObject().getAsJsonObject("images");
JsonObject lowResolution = images.getAsJsonObject("low_resolution");
String url = lowResolution.getAsJsonPrimitive("url").getAsString();
System.out.println(url);
}
Using your example JSON, this would print:
https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2

Expected BEGIN_OBJECT but was STRING - json without key

I'm generally a beginner in Android and json, and I'm stuck on one part and need some help. I'm trying to use Rotten Tomatoes json. I managed read almost everything, except the part where there isn't key in json. Here is the json:
{
"movies": [{
"id": "771359313",
"title": "Dumb and Dumber To",
"year": 2014,
"mpaa_rating": "PG-13",
"runtime": 109,
"critics_consensus": "",
"release_dates": {
"theater": "2014-11-14"
},
"ratings": {
"critics_rating": "Rotten",
"critics_score": 25,
"audience_rating": "Spilled",
"audience_score": 54
},
"synopsis": "Jim Carrey and Jeff Daniels reprise their signature roles as Lloyd and Harry in the sequel to the smash hit that took the physical comedy and kicked it in the nuts: Dumb and Dumber To. The original film's directors, Peter and Bobby Farrelly, take Lloyd and Harry on a road trip to find a child Harry never knew he had and the responsibility neither should ever, ever be given. The Farrelly brothers produce Dumb and Dumber To alongside Riza Aziz and Joey McFarland of Red Granite Pictures. They are joined by fellow producers Charles B. Wessler and Bradley Thomas. Universal Pictures will distribute the film in the United States, Canada and select international territories.(C) Universal",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg",
"profile": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg",
"detailed": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg",
"original": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg"
},
"abridged_cast": [{
"name": "Jim Carrey",
"id": "162659418",
"characters": ["Lloyd Christmas"]
}, {
"name": "Jeff Daniels",
"id": "162654392",
"characters": ["Harry Dunne"]
}, {
"name": "Kathleen Turner",
"id": "162658757",
"characters": ["Fraida Felcher"]
}, {
"name": "Rob Riggle",
"id": "770750133",
"characters": ["Travis/Captain Lippincott"]
}, {
"name": "Jennifer Lawrence",
"id": "770800260",
"characters": ["Young Fraida Felcher"]
}],
"alternate_ids": {
"imdb": "2096672"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313.json",
"alternate": "http://www.rottentomatoes.com/m/dumb_and_dumber_to/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313/similar.json"
}
}, {
"id": "771355766",
"title": "Big Hero 6",
"year": 2014,
"mpaa_rating": "PG",
"runtime": 93,
"critics_consensus": "",
"release_dates": {
"theater": "2014-11-07"
},
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": 89,
"audience_rating": "Upright",
"audience_score": 94
},
"synopsis": "With all the heart and humor audiences expect from Walt Disney Animation Studios, \"Big Hero 6\" is an action-packed comedy-adventure about robotics prodigy Hiro Hamada, who learns to harness his genius-thanks to his brilliant brother Tadashi and their like-minded friends: adrenaline junkie Go Go Tamago, neatnik Wasabi, chemistry whiz Honey Lemon and fanboy Fred. When a devastating turn of events catapults them into the midst of a dangerous plot unfolding in the streets of San Fransokyo, Hiro turns to his closest companion-a robot named Baymax-and transforms the group into a band of high-tech heroes determined to solve the mystery. (C) Disney",
"posters": {
"thumbnail": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg",
"profile": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg",
"detailed": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg",
"original": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg"
},
"abridged_cast": [{
"name": "Ryan Potter",
"id": "771360315",
"characters": ["Hiro Hamada"]
}, {
"name": "Scott Adsit",
"id": "406975480",
"characters": ["Baymax"]
}, {
"name": "T.J. Miller",
"id": "770690115",
"characters": ["Fred"]
}, {
"name": "Jamie Chung",
"id": "770694653",
"characters": ["Go Go Tomago"]
}, {
"name": "Damon Wayans Jr.",
"id": "770822247",
"characters": ["Wasabi"]
}],
"alternate_ids": {
"imdb": "2245084"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766.json",
"alternate": "http://www.rottentomatoes.com/m/big_hero_6/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766/similar.json"
}
}],
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=2&country=us",
"alternate": "http://www.rottentomatoes.com/movie/box-office/"
},
"link_template": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit={num-results}&country={country-code}"
}
Now, I managed to get name, id, but not the characters. Here are some parts of the code how I got it to work:
public class Movie {
String actor_name;
public Movie(String response, int index) {
Gson gson = new Gson();
MoviesContainer movie = gson.fromJson(response.trim(), MoviesContainer.class);
List < MovieData > movies = movie.movie
AbridgedCastData[] aCast = gson.fromJson(gson.toJson(movies.get(index).abridged_cast), AbridgedCastData[].class);
actor_name = aCast[0].name;
}
}
class MovieData {
Object abridged_cast;
}
class MoviesContainer {
public List < MovieData > movies;
}
class AbridgedCastData {
String name;
String id;
Object characters;
}
I'm using directly index for testing purposes, so actor_name works perfectly.
I tried like this :
CharactersData[] character = gson.fromJson(gson.toJson(aCast[0].characters), CharactersData[].class);
But I'm getting error:
Expected BEGIN_OBJECT but was STRING
I searched everywhere but I can't find how to access characters. How to get for example character Lloyd Christmas? Thanks in advance.
First of all your JSON file is not valid. It should begin with { and end with }. You can check with an online validator such as JSONLint. That's why you get this error.
Secondly if you look at the structure of the file, you see that there is an an array called abridged_cast which contains some objects (which you defined fine in your AbridgedCastData class).
So the final structure could be:
class A {
//contains a list of objects B or an array of objects B
}
class B {
//name
//id
//characters (list of Strings or String array)
}
We are almost done!
When you don't specify a SerializedName annotation, the parser requires that the field name of the attribute you want to serialize must be the same as in the JSON file (otherwise you will end up with a non-initialized value). Since that's not the case you need to add a #SerializedName("abridged_cast") annotation.
Finally you end up with:
public class Test {
public static void main(String[] args) throws FileNotFoundException {
BufferedReader br = new BufferedReader(new FileReader("myJson.json"));
Gson gson = new Gson();
MoviesContainer movie = gson.fromJson(br, MoviesContainer.class);
List<AbridgedCastData> movies = movie.movies;
System.out.println(movies);
}
}
class MoviesContainer {
#SerializedName("abridged_cast")
public List<AbridgedCastData> movies;
}
class AbridgedCastData {
String name;
String id;
List<String> characters;
#Override
public String toString() {
return "AbridgedCastData [name=" + name + ", id=" + id
+ ", characters=" + characters + "]";
}
}
Which outputs:
[AbridgedCastData [name=Jim Carrey, id=162659418, characters=[Lloyd Christmas]], AbridgedCastData [name=Jeff Daniels, id=162654392, characters=[Harry Dunne]], AbridgedCastData [name=Kathleen Turner, id=162658757, characters=[Fraida Felcher]], AbridgedCastData [name=Rob Riggle, id=770750133, characters=[Travis/Captain Lippincott]], AbridgedCastData [name=Jennifer Lawrence, id=770800260, characters=[Young Fraida Felcher]]]
you could change your response and then parse it.
response = "{" + response + "}" ;
// now parse json

Categories

Resources