简体   繁体   中英

How to read/write Object to JSON file with jackson in Java

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;
}

I am trying to write the Town class to JSON using

ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
 writer.writeValue(out, townobj);

Which produces Json like this.

{
  "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
}

When I try to read this using

List<Town> myObjects;       
myObjects = mapper.readValue(new File("test.json"), new TypeReference<List<Town>>(){});

I get the following error:

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

The JSON in your file is not a valid array in order to deserialize it to List<Town> . You need to serialize a list to JSON in order to deserialize it back to a list:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM