如何将JSON数组转换为Java列表。我在用斯文森
我试图在Java中将多个相同类型的对象转换为List
。例如,我的json是:
{
"Example": [
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
{
"foo": "a3",
"bar": "b3",
"fubar": "c3"
}
]
}
我有一门课:
public class Example {
private String foo;
private String bar;
private String fubar;
public Example(){};
public void setFoo(String f){
foo = f;
}
public void setBar(String b){
bar = b;
}
public void setFubar(String f){
fubar = f;
}
...
}
我希望能够将得到的json字符串转换为Example
对象列表。我想这样做:
JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
List<Example> result = parser.parse(List.class, json);
这样做会出现一个错误:
Cannot set property Example on class java.util.ArrayList
# 1 楼答案
我通过修改JSON的格式解决了这个问题:
然后我使用了java代码:
# 2 楼答案
我有一个类似这样的JSON字符串:
并通过以下代码片段将其转换为列表:
我用网。旧金山。json lib jar文件