0

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?

payton
  • 5
  • 3

2 Answers2

0

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.

Azim
  • 1,043
  • 13
  • 27
0

If you really want to have String[][] users back, you need to use serializer or deserializer to achieve it. I used Oson library to do this:

        String jsonString = "[{\"user_name\":\"Azim\",\"zip_code\":67890},{\"user_name\":\"Smith\",\"zip_code\":12345}]";

        String[][] users = oson.des(String[].class, (Object p) -> StringUtil.list2Array(((Map)p).values()))
                .deserialize(jsonString, String[][].class);

        String json = oson.serialize(users);
        String expected = "[[\"Azim\",\"67890\"],[\"Smith\",\"12345\"]]";
        assertEquals(expected, json);
David He
  • 54
  • 4