user1047833
user1047833

Reputation: 343

Parsing JSON array with gson

I am having trouble parsing my JSON which i get from javascript. The format of JSON is this:

[{"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 been able to get this far:

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

But i also need to now create a class with those positions. I havnt been working on the class, since i tried printing out the output first, but i am unable to break it down further. I am getting this error message:

java.lang.IllegalStateException: This is not a JSON Array.

And my code is this:

    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 have also tried to do it this way:

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

In which case i get:

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

In the end, i want to loop through positions, creating class for each "positions", which contains a List with another class Position, which has the int x, y.

Thank you for your time.

Upvotes: 3

Views: 11635

Answers (1)

Boris Strandjev
Boris Strandjev

Reputation: 46943

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

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

And the inner class:

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

Now you can parse a json string of the outer class just like that:

gson.fromJson(jsonString, Class1.class);

Your error while using Gson is that you try to parse a complex object in String, which is not possible.

Upvotes: 8

Related Questions