Reputation: 3
Hi all I have been trying to parse the above JSON into a java program and store it into an object... (Don't have a specific structure at the moment, as long as I can get the data from the object.)
Have been trying to use GSON but I can't seem to get it right..
String inputLine="";
HttpClient httpclient= new DefaultHttpClient();
HttpGet method = new HttpGet("http://localhost:3000/specs/215/errors.js");
HttpResponse response =httpclient.execute(method);
BufferedReader in = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(inputLine).getAsJsonArray();
for(int i=0; i < array.size(); i++) {
Errors e = gson.fromJson(array.get(0), Errors.class);
System.out.println(e.error.getReason());
}
and the error i get is:
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:99)
at test.Getter.main(Getter.java:37)
Anyone please point me in the right direction? Thanks.
Upvotes: 0
Views: 7406
Reputation: 11
I fixed the issue I had. Novice mistake with the serialized annotations. For some reason I thought they would reference the name of the class not the field names. But more importantly, I also had to create a root-level container class to hold my classes. That allowed for all the objects to be parsed.
Upvotes: 0
Reputation: 168
JSON Structures are realized as an object, record,struct, dictionary, hash table, keyed list, or associative array.
You can use eval() function to achieve the desired goal. I think this will help you/
Upvotes: 0
Reputation: 89169
The JSON String is not a JSON Array String. JSON String starts and ends with {
, }
respectively while JSON Array starts and ends with [
, ]
respectively.
This line is wrong:
JsonArray array = parser.parse(inputLine).getAsJsonArray();
Rather retrieve it as a JsonObject
.
Upvotes: 3