我正在尝试从JSON字符串反序列化Java对象。我正在尝试使用Gson API,但我不了解如何在Java对象中实现这种JSON结构:
{
"set1" : [
[[0], [1], [2], [3], [4]],
[[0,1], 2, 3, 4],
[[0,1], 2, [3,4]],
[[0,1], [2,3,4]],
[[0,1,2,3,4]]
],
"set2" : [
[0, 1, 2, 3, 4],
[0, 2, 3, 4],
[0, 2, 3],
[0, 2]
[0]
],
"num" : 2345
}
特别是我无法理解如何实现“ set1”和“ set2”。从理论上讲,第一个是int大小不同的数组的数组,第二个是int大小不同的数组的数组。因此,我尝试将它们实现为ex。set1,List <List <Integer >> [],但它也不起作用。
有谁关于如何使用Gson或其他Java API的一些技巧?非常感谢。
好的,所以我绝对是Gson的忠实用户:
Gson将自动尝试填充它在对象中找到的字段。
如果我有这个:
public class Foo {
public String string;
}
和这个JSON
{
"string": "contents"
}
然后Gson会将“内容”放入Foo
“字符串”字段,因为它们的名称相同,并且类型相同。
String string = "contents"
您可以做这样的事情(刚刚测试过)
public class Test {
// Your JSON string (with 'n's replaced with definite values)
public static final String JSON = "{\"set1\":[[[1],[2]],[[3,4]]],\"set2\":[[1,2],[3]],\"num\":10}";
public static void main(String[] args) {
// New basic Gson instance
Gson gson = new Gson();
// New blank object
JsonExample example;
// Deserialize the JSON into Java
example = gson.fromJson(JSON, JsonExample.class);
//Print the results
System.out.println(example.set1);
System.out.println(example.set2);
System.out.println(example.num);
}
public static class JsonExample {
// The same number of Lists as []s in JSON
// You need to know this number before hand because Java is
// ... strongly typed.
List<List<List<Integer>>> set1;
List<List<Integer>> set2;
// Basic Integer
Integer num;
}
}
// Output
[[[1], [2]], [[3, 4]]]
[[1, 2], [3]]
10
如果Gson可以轻松推断其必须执行的操作,则Gson只会执行“自动输入”,即,如果您有一个String字段,那么您可能想要一个与该字段同名的String。它甚至足够聪明,可以推断整个Java对象。
例如,这两个是等效的:
// A class containing a complex object
public static class ComplexObject {
InnerObject obj;
}
public static class InnerObject {
String string;
}
// Its JSON representation, as understood by Gson
{
"obj" : {
"string": "contents"
}
}
因此,就像您的问题一样,正如我上面所说的,您可以使用<T> object = Gson.fromJson(String)
JSON字符串将其解析为Java对象,并且您的类如下所示:
public static class JsonExample {
// The same number of Lists as []s in JSON
// You need to know this number before hand because Java is
// ... strongly typed.
List<List<List<Integer>>> set1;
List<List<Integer>> set2;
// Plain integer
Integer num;
}
我希望这有帮助。请问任何需要澄清或问题的地方,我很乐意进行编辑或阐述。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句