查询数据库有如下的查询结果
name id remark time data type contain
张三 1 测试 2016 数据1 test1 1
张三 1 测试 2016 数据2 test2 1
张三 1 测试 2016 数据3 test3 1
张三 1 测试 2016 数据4 test4 1
李四 2 测试2 2016 数据99 test66 0
李四 2 测试2 2016 数据98 test66 0
......
现在我想处理数据,形成如下格式
[{name:张三,remark:测试,time:2016,display:[{data:数据1,type:test1},{data:数据2,type:test2},{data:数据3,type:test3},{data:数据4,type:test4}]},{name:李四,remark:测试2,time:2016,display:[{data:数据99,type:test66},[{data:数据98,type:test66}]}]
需要一个比较方便的方法,手动拼接就算了,感谢。
[
{
name: 张三,remark:测试,time:2016,display: [
{
data: 数据1,type: test1
},
{
data: 数据2,type: test2
},
{
data: 数据3,type: test3
},
{
data: 数据4,type: test4
}
]
},
{
name: 李四,remark:测试2,time:2016,display: [
{
data: 数据99,type: test66
},
[
{
data: 数据98,type: test66
}
]
}
]
想到用hashmap,不过没实现,请教各位指点下
The questioner raised this question because there is no concept of serialization and deserialization yet.
Serialization is the process of converting an object into data in a specific format, such as converting a java instance into an xml or json (or other specification) string. The deserialization process is the opposite, converting an xml, json (or other specification) into a java object.
Specifically for the serialization and deserialization of json, I personally think there are two ways
1. Implement it yourself, such as using reflection and other methods to complete this method. In the end, you still need to splice strings, which is your own wheel.
2. Use Existing json libraries, such as gson, jackson, fastjson, etc., provide relatively simple serialization and deserialization interfaces.
For example, using fastjson, serialization can be implemented in this style (pseudocode)
Deserialization is similar
There are many Java libraries that generate JSON, such as fastjson (oschina introduction page)
Gson
Jackson
Fastjson
Search Gson
First assemble it into a Java Bean, and then use some JSON serialization tools, commonly used ones include
Jackson,fastjson,Gson
etc.You can use hashmap, put it in the list, then put it in the map, and convert it through Gson.
For example
Map<String,Stirng> nameMap = new HashMap<String,String>();
nameMap .put(name,"Zhang San");
nameMap .put(remark,"Salesperson");
Map<String ,Stirng> dataMap= new HashMap<String,String>();
List dataList =new ArrayList();
for(int i=0;i<=4;i++){
dataMap.put("data"," data1");
dataMap.put("type","666");
}
dataList.add(dataMap);
nameMap.put(display,dataList);
String s = new Gson().toJson( nameMap);
The code should work with a slight adjustment.
You can try various tools. Gson is a good choice
Java has so many ways to serialize objects into json strings, why not use them