I am fairly new to Java and I have tried looking up an answer for this for the last couple hours and so far I have nothing.
I am working with the Nobel Prize API for a project and I am getting an error when I try to convert to classes from the Json stream.
My code to read in the stream is this:
Gson gson = new Gson();
String sURL = "http://api.nobelprize.orgv1/laureate.json?bornCountry=Canada"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
LaureatesMain person = gson.fromJson(rootobj, LaureatesMain.class);
System.out.println(person);
}
I am not checking for errors from the stream yet.
The json stream that I am looking at looks something like this:
{
"laureates": [
{
"id": "140",
// MORE STUFF
"prizes": [
{
"year": "1990",
// MORE STUFF
"affiliations": [
{
"name": "Stanford University",
"city": "Stanford, CA",
"country": "USA"
}
]
}
]
}
]
}
I have a class for the laureates, prizes and affiliations and when it runs on Json like above I have no issue and it goes into the classes fine.
The problem I run into is if there is no entry in the affiliations then for some reason the API flips the {} to [] and gives me the following:
{
"laureates": [
{
"id": "140",
// MORE STUFF
"prizes": [
{
"year": "1990",
// MORE STUFF
"affiliations": [[]
]
}
]
}
]
}
When I run on this one I get Expected BEGIN_OBJECT
but was BEGIN_ARRAY
at path
$.laureates[###].prizes[0].affiliations[0]
I have tried looking at changing the GsonBuilder
and tried to intercept the Json and change it before it goes into the Builder
but so far nothing has worked for me.
I have no control over what I get from the API. I can deal with it being an empty class object or a null value in the final structure. This is a fairly early iteration of the project but so far this issue is stopping me from moving on to other things.
Thanks