简体   繁体   English

用gson解析JSON数组

[英]Parsing JSON array with gson

I am having trouble parsing my JSON which i get from javascript. 我无法解析我从javascript获得的JSON。 The format of JSON is this: JSON的格式是这样的:

[{"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. java.lang.IllegalStateException:这不是JSON数组。

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 com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期的STRING但是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. 最后,我想循环遍历位置,为每个“位置”创建类,其中包含具有另一个类Position的List,其具有int x,y。

Thank you for your time. 感谢您的时间。

Define your classes and you will get everything you need using gson: 定义您的类,您将获得使用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: 现在你可以像这样解析外部类的json字符串:

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. 使用Gson时的错误是您尝试在String解析复杂对象,这是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM