JSON:嵌套数组 [英] JSON: Nested Array

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

问题描述

我有一个从数据库中检索数据的程序(JSON MySQL中的数据存储)。

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:

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}

谢谢。

推荐答案

你可以使用Jackson Api来实现这一点。

你必须创建与你的json对象相同的Pojo类(类应该有像'attributes','uuid'这样的成员。)
这是你必须使用的课程

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;

和代码

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

现在你可以使用Mapperclass的getter方法来获取java对象或数组等中的json属性,如

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

 String uuid=mapper.getUuid();

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆