本文介绍了JSON 数组到 Java 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析如下所示的 JSON 文件:

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

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

public class 点击{整数 x;输入 y;公共点击(int x,int y){this.x = x;这.y = y;}公共 int getX() {返回 x;}公共无效 setX(int x) {this.x = x;}公共 int getY() {返回 y;}公共无效 setY(int y) {这.y = y;}}

我看过 gson,因为他们说它很容易,但我不知道如何从我的文件中做到这一点.

解决方案

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

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

I need to parse a JSON file which looks like this:

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

And I want to put these X-coordinates and Y-coordinates into an JavaObject Click, that class looks like this:

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;
    }
}

I have looked at gson because they say it is quit easy, but I don't get it how I can do it from my file.

解决方案

assuming your json string data is stored in variable called jsonStr:

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

这篇关于JSON 数组到 Java 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 11:17