Gametron Gametron - 1 month ago 4
JSON Question

Parse JSON to Java 2-D Array

I am trying to parse JSON whose format looks like this:

{"user_name":"","zip_code":null}
{"user_name":"","zip_code":null}
{"user_name":"","zip_code":null}
{"user_name":"","zip_code":null}


It displays the amount of users in a certain database. However, the number of users will be unknown.

What I would like to do is assign each user and their data to their own array in a 2-d array

String[][] users = new String[USER_AMOUNT][2];


(2 for the user_name and zip_code)

Is there a way to do that with the given format of JSON?

Answer

Yes, there is a way, you can use Gson library for achieving the same.

First define a POJO(Plain Old Java Object) with the same fields as of Json you have.

public class User {

    private String user_name;
    private String zip_code;

    public String getZip_code() {
        return zip_code;
    }

    public void setZip_code(String zip_code) {
        this.zip_code = zip_code;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
}

And then write the driver class:

import com.google.gson.Gson;

public class JsonToJavaObjMapper {

    public static void main(String[] args) {
        String jsonString = "{\"user_name\":\"Azim\",\"zip_code\":null}";
        Gson gson = new Gson();
        User fromJson = gson.fromJson(jsonString, User.class);
        System.out.println(fromJson.getUser_name() + " " + fromJson.getZip_code());
    }
}

Include the gson jar into your classpath and run the above class.

Output:

Azim null

Maybe this piece of code would be helpful to you.

Comments