如何使用Java中的jackson读取/写入Object到JSON文件

时间:2017-05-18 11:16:56

标签: java json jackson

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类编写为JSON
ObjectMapper 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的实例

1 个答案:

答案 0 :(得分:0)

文件中的JSON无效,无法将其反序列化为List<Town>。您需要将列表序列化为JSON,以便将其反序列化回列表:

writer.writeValue(out, Arrays.asList(townobj));