java 使用 gson 解析 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9853017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:39:07  来源:igfitidea点击:

Parsing JSON array with gson

javajsongsonarrays

提问by user1047833

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

我在解析我从 javascript 获得的 JSON 时遇到问题。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.

感谢您的时间。

回答by Boris Strandjev

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,这是不可能的。