public class Town implements Serializable{
private Person p;
private String hello;
private long number;
}
public class Person implements Serializable {
private String firstName;
private double legs;
private String lastName;
}
我正在尝试使用
将Town类编写为JSONObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
writer.writeValue(out, townobj);
这就产生了Json。
{
"p" : {
"firstName" : "John",
"amount" : 6860.0,
"lastName" : "Smith"
},
"hello" : "qwiejiowcqnio",
"number" : 1380.0
}
{
"p" : {
"firstName" : "Sam",
"amount" : 623460.0,
"lastName" : "Smith"
},
"hello" : "qwiej2342io",
"number" : 1330.0
}
当我尝试使用
阅读本文时List<Town> myObjects;
myObjects = mapper.readValue(new File("test.json"), new TypeReference<List<Town>>(){});
我收到以下错误:
无法从START_OBJECT标记中反序列化java.util.ArrayList的实例
答案 0 :(得分:0)
文件中的JSON无效,无法将其反序列化为List<Town>
。您需要将列表序列化为JSON,以便将其反序列化回列表:
writer.writeValue(out, Arrays.asList(townobj));