Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

java - JSON: Nested Array

I have a program that retrieves data from a Database (data store in JSON MySQL).

public static int selectData(Connection conn, String db_type) throws SQLException {

     JSONObject obj = new JSONObject();

    String q = "SELECT * FROM common_attr_test";
        PreparedStatement preparedStatement = conn.prepareStatement(q);
        preparedStatement.execute();
        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
                String uuid_user = rs.getString("uuid");
                String attributes_uuid = rs.getString("attributes");

                obj.put("uuid", uuid_user);
                obj.put("attributes",  attributes_uuid);  
        }

            System.out.println("JSON Obj: "+obj);

    return 1;
 } // end selectData function

I managed to get the object. The output is:

JSON Obj:

 {
  "attributes": "{"1": {"1": 2, "2": 2, "3": 3}, "2": {"h4y4/1123": 4, "h4yp:/4/1123": 1, "h4yyp:/4/1123": 1, "httyyyyp:/4/1123": 1}, "3": {"Chrome|Windows NT 6.1": 7}, "7": {"2": 4, "6": 1}, "8": {"1": 1, "2": 1, "3": 1, "4": 1, "5": 1, "6": 1, "7": 1}}",
  "uuid": "izyani1234561"
}

I need a suggestion on how I can process the data and put the information in different array/object. For example

    array1 - 1:{1:2, 2:2, 3:3}
    array2 - 7:{2:4, 6:1}
    array3 - 8:{1:1, 2:1, 3:1, 4:1, 5:1, 6:1, 7:1}

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Jackson Api to achieve this.
You have to create Pojo class same as your json object (Class should have members like 'attributes','uuid').
This are classes you have to use

com.fasterxml.jackson.core.JsonFactory;
com.fasterxml.jackson.core.JsonParser;
com.fasterxml.jackson.databind.ObjectMapper;

And code

ObjectMapper objMapper=new ObjectMapper();
JsonFactory jfactory = new JsonFactory();
JsonParser jParser=jfactory.createJsonParser(jsonString); //json Object as String

Mapperclass mapper=objMapper.readValue(jParser,Mapperclass.class);// Mapperclass is Pojo for your jsonObject

Now you can use getter methods of Mapperclass to get you json attributes in java object or Arrays etc like

 String uuid=mapper.getUuid();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...