我想读取一个json数组,并在可能的情况下将其放入int三维数组中。
数据看起来像这样,我可以改变它的设计以满足我的需求,因为它尚未完成。这些值是愚蠢的,但有什么好处可以知道(提前注意*前面)我必须嵌套一个包含整数的未知数量的数组,在一个重复三次或更少的数组中两次在根节点中。
即。 int[3 or less][2][unknown int] = val
我编写了提高可读性的密钥,它们可能也可能不是实际json的一部分。
{
demand : {
0 : {
0 :{
0 :22,
1 :32,
2 :21
},
1 :{
0 :2762,
1 :352,
2 :231
}
},
1 :{
0 :{
0 :222,
1 :232,
2 :621
},
1 :{
0 :272,
1 :37762,
2 :261
}
}
}
}
重点是键和值都是整数,我想用它创建int [][][]
。我认为答案在于此文档:Jackson Full Databinding,但我不能正确理解它对我的数据有何用处。
我正在考虑一些ObjectMapper.readValue(json,new TypeReference>(){})`并将继续研究这个问题,但我没有太多希望。
感谢您的帮助!
编辑以下是实际有效的JSON
[ [ [ 22, 32, 21 ], [ 2762, 352, 231 ] ], [ [ 222, 232, 621 ], [ 272, 37762, 261]] ]
答案 0 :(得分:4)
使用Jackson序列化/反序列化数组与序列化任何其他内容相同:
public class App
{
public static void main(String[] args) throws JsonProcessingException {
int[][][] a = new int[2][3][2];
a[0][2][0] = 3;
ObjectMapper om = new ObjectMapper();
// Serialize to JSON
String json = om.writeValueAsString(a);
System.out.println(json);
// deserialize back from JSON
a = om.readValue(json, int[][][].class);
System.out.println(a[0][2][0]);
}
}
输出:
[[[0,0],[0,0],[3,0]],[[0,0],[0,0],[0,0]]]
3
那就是说,除非你知道它总是一个三维数组,否则你最好使用List
s
答案 1 :(得分:0)
我不确定这是否能回答你的问题,但我认为你总是可以使用迭代器和拆分,例如:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.sf.json.JSONObject;
public class test {
/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Map <String, Object> map1 = new HashMap<String, Object>();
Map <String, Object> map2 = new HashMap<String, Object>();
Map <String, Map> map3 = new HashMap<String, Map>();
map1.put("0","22,32,21");
map1.put("1", "2762,352,231");
map2.put("0", "222,232,621");
map2.put("1","272,37762,261");
map3.put("0",map1 );
map3.put("1",map2);
JSONObject jsonobj = JSONObject.fromObject(map3); // creating json object
Iterator it = jsonobj.keys();
int maxZ = 0; //find out the length of the last dimension
while(it.hasNext()) {
JSONObject jobj = (JSONObject) jsonobj.get(it.next());
Iterator it2 = jobj.keys();
while(it2.hasNext()) {
if(((String)jobj.get(it2.next())).split(",").length > maxZ){
maxZ= ((String)jobj.get(it2.next())).split(",").length;
}
}
}
int[][][] result= new int [jsonobj.size()][2][maxZ]; //creating 3D array of the right size
int x = 0, y = 0, z = 0;
it = jsonobj.keys();
while(it.hasNext()) {
JSONObject jobj = (JSONObject) jsonobj.get(it.next());
Iterator it2 = jobj.keys();
y = 0; //reset y
while(it2.hasNext()) {
String[]s =((String)jobj.get(it2.next())).split(",");
z = 0; //reset z
for (String str : s) {
result[x][y][z] = Integer.parseInt(str);
z++;
}
y++;
}
x++;
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++) {
System.out.print(result[i][j][k]);
System.out.print(" ");
}
System.out.println("\n");
}
}
}
}
输出:
272 37762 261
222 232 621
2762 352 231
22 32 21
不确定为什么这是在后面的顺序,对不起,如果这没有帮助:P