JSON 数组到 Java 对象

2022-09-03 12:14:01

我需要解析一个JSON文件,如下所示:

[
  {
    "y": 148, 
    "x": 155
  }, 
  {
    "y": 135, 
    "x": 148
  }, 
  {
    "y": 148, 
    "x": 154
  }
]

我想把这些 X 坐标和 Y 坐标放到 JavaObject Click 中,该类如下所示:

public class Click {
    int x;
    int y;

    public Click(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

我看过gson,因为他们说它很容易退出,但我不明白如何从我的文件中做到这一点。


答案 1

假设您的 json 字符串数据存储在名为 :jsonStr

String jsonStr = getJsonFromSomewhere();
Gson gson = new Gson();
Click clicks[] = gson.fromJson(jsonStr, Click[].class);

答案 2

查看 Gson API 和一些示例。我已经把链接放在下面!

String jsonString = //your json String
Gson gson = new Gson();
Type typeOfList = new TypeToken<List<Map<String, Integer>>>() {}.getType();
List<Map<String, Integer>> list = gson.fromJson(jsonString, typeOfMap);

List<Click> clicks = new ArrayList<Click>();
for(int i = 0; i < list.size(); i++) {
    int x = list.get(i).get("x");
    int y = list.get(i).get("y");
    clicks.add(new Click(x, y));
}

(http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html)(http://google-gson.googlecode.com/svn/tags/1.5/src/test/java/com/google/gson/functional/MapTest.java)