3

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.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
user1047833
  • 343
  • 2
  • 7
  • 17

1 Answers1

8

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.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Thank you very much. I never thought it would be this easy and i dont even know what i wanted to do with the String. You are my hero – user1047833 Mar 24 '12 at 18:00
  • Hi is it possible to parse a complex JSON string created in PHP having mixed dataTypes without creating inner classes. Actually our API is written in PHP and we are using that API through a java app. – Sumit Kumar Feb 23 '15 at 12:59
  • @sumit: how do you want to consume the JSON string? While JSON is the object format in PHP / javascript how would you access the properties in java? – Boris Strandjev Feb 23 '15 at 14:17
  • I just found solution here http://stackoverflow.com/questions/16595493/gson-parsing-without-a-lot-of-classes – Sumit Kumar Feb 23 '15 at 14:31