Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Array to Java objects

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.

like image 254
ProblemAnswerQue Avatar asked Dec 23 '14 21:12

ProblemAnswerQue


2 Answers

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);
like image 190
Yazan Avatar answered Oct 10 '22 10:10

Yazan


Check out the Gson API and some examples. I've put the links below!

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)

like image 2
haley Avatar answered Oct 10 '22 10:10

haley