Parsing a JSON array with gson

I am having trouble parsing my JSON, which I get from javascript. The JSON format is as follows:

[{"positions":[{"x":50,"y":50},{"x":82,"y":50},{"x":114,"y":50},{"x":146,"y":50}]},{"positions":[{"x":210,"y":50},{"x":242,"y":50},{"x":274,"y":50}]}] 

So far I have managed to go this far:

 {"positions":[{"x":50,"y":50},{"x":82,"y":50},{"x":114,"y":50},{"x":146,"y":50}]} 

But I also need to create a class with such positions. I havnt worked on the class since I first tried to print the output, but I cannot break it further. I get this error message:

java.lang.IllegalStateException: this is not a JSON array.

And my code is:

  JsonParser parser = new JsonParser(); String ships = request.getParameter("JSONships"); JsonArray array = parser.parse(ships).getAsJsonArray(); System.out.println(array.get(0).toString()); JsonArray array2 = parser.parse(array.get(0).toString()).getAsJsonArray(); System.out.println(array2.get(0).toString()); 

I also tried to do this as follows:

  Gson gson = new Gson() ; String lol = (gson.fromJson(array.get(0), String.class)); System.out.println(lol); 

In this case, I get:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: STRING expected but BEGIN_OBJECT

In the end, I want to iterate over the positions, creating a class for each "position" that contains a list with another Position class that has int x, y.

Thank you for your time.

+3
source share
1 answer

Define your classes and you will get everything you need using gson:

 public class Class1 { private int x; private List<Class2> elements; } 

And inner class:

 public class Class2 { private String str1; private Integer int2; } 

Now you can parse the json string of the outer class like this:

 gson.fromJson(jsonString, Class1.class); 

Your mistake when using Gson is that you are trying to parse a complex object into a String , which is not possible.

+8
source

All Articles