Java 将resultset映射到json
我有一些结果集数据如下:Java 将resultset映射到json,java,json,resultset,Java,Json,Resultset,我有一些结果集数据如下: +-------+-------+-------+-------+ | Code1 | Code2 | Code3 | Code4 | +-------+-------+-------+-------+ | 1 | 11 | 111 | 1111 | | 2 | 21 | 211 | 2111 | | 2 | 22 | 221 | 2211 | | 2 | 21 | 212 | 2121 |
+-------+-------+-------+-------+
| Code1 | Code2 | Code3 | Code4 |
+-------+-------+-------+-------+
| 1 | 11 | 111 | 1111 |
| 2 | 21 | 211 | 2111 |
| 2 | 22 | 221 | 2211 |
| 2 | 21 | 212 | 2121 |
+-------+-------+-------+-------+
我需要将上述结果集转换为以下两个JSON
code1_code2 = {
1 : [11],
2 : [21, 22, 21]
};
code2_code3 = {
11 : [111],
21 : [211, 212],
22 : [221]
};
我尝试过解析结果集,当第一列排序时,我可以得到第一个json。
但是由于第二列没有排序,我无法获得第二个json
(注意:-我不会订购第二列)您必须首先构建树结构。然后,在树的每一层,您都将输出为JSON。这基本上是BFS的微小变化(也称为级别顺序遍历)。注意 的名称/值对中的名称应为字符串(而不是问题中的数字)
(来源:) 示例代码 正如@josnidhin的评论中提到的,无论结果集是否有序,都可以使用
Map
来存储这些数据
下面是一个示例代码,我选择处理JSON内容
package test;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import net.sf.json.*;
public class StackOverflowQ10976771_ResultSetToJSON
{
public static void appendValue (Map<String, List<Integer>> map, String key, int value)
{
List<Integer> values = map.get (key);
if (values == null)
{
values = new ArrayList<Integer> ();
map.put (key, values);
}
values.add (value);
}
public static void main (String[] args)
{
Map<String, List<Integer>> code1_code2 = new ConcurrentSkipListMap<String, List<Integer>> ();
Map<String, List<Integer>> code2_code3 = new ConcurrentSkipListMap<String, List<Integer>> ();
Map<String, List<Integer>> code3_code4 = new ConcurrentSkipListMap<String, List<Integer>> ();
int[][] sample_resultSet = {
{1, 11, 111, 1111},
{2, 21, 211, 2111},
{2, 22, 221, 2211},
{2, 21, 212, 2121},
};
//ResultSet rs = null;
//while (rs.next ())
for (int[] rs : sample_resultSet)
{
appendValue (code1_code2, String.valueOf(rs[0]), rs[1]);
appendValue (code2_code3, String.valueOf(rs[1]), rs[2]);
appendValue (code3_code4, String.valueOf(rs[2]), rs[3]);
}
System.out.println ("code1_code2 =");
System.out.println (JSONObject.fromObject (code1_code2).toString(4 ,4) + ";");
System.out.println ();
System.out.println ("code2_code3 = ");
System.out.println (JSONObject.fromObject (code2_code3).toString(4 ,4) + ";");
System.out.println ();
//System.out.println ("code3_code4 = ");
//System.out.println (JSONObject.fromObject (code3_code4).toString(4 ,4) + ";");
//System.out.println ();
}
}
编写一个循环,将值转换为数据结构(可能是hashmap),并使用一些json库(可能是GSON)将其转换为json
code1_code2 =
{
"1": [11],
"2": [
21,
22,
21
]
};
code2_code3 =
{
"11": [111],
"21": [
211,
212
],
"22": [221]
};