JSON Array to Java对象

我需要解析一个看起来像这样的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,因为他们说它很容易退出,但我不知道如何从我的档案中做到这一点。

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

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

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

 String jsonString = //your json String Gson gson = new Gson(); Type typeOfList = new TypeToken>>() {}.getType(); List> list = gson.fromJson(jsonString, typeOfMap); List clicks = new ArrayList(); 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 )

另一个可靠的选择是jackson,它似乎有一个非常可靠的教程。 我不熟悉它,所以我希望这会有所帮助。

主要思想是它使用对象映射器

 ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(new File("c:\\user.json"), User.class); 

第4步应该是你最好的选择,只是意识到你可能想要User.class以外的东西

编辑:

如果您已经开始使用Gson,那么查看其他类似的答案也会有所帮助。 这个问题是关于将JSON转换为POJO(普通旧Java对象),它们更像是漂浮在它周围。 再说一遍,我对这些并不是很熟悉,我可以尝试回答一些问题,但我希望这能让你找到你需要去的地方。

快乐的编码! 如果您有任何疑问,请发表评论。