如何读写Java对象到JSON文件?
以下示例演示如何将Java对象序列化和反序列化为JSON文件。Jackson的ObjectMapper类提供writeValue(File,Object)和readValue(File,Class<T>)方法,使我们可以分别将对象写入JSON文件和将JSON文件读取到对象。
package org.nhooo.example.jackson;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class ObjectToJsonFile {
public static void main(String[] args) {
Artist artist = new Artist();
artist.setId(1L);
artist.setName("The Beatles");
ObjectMapper mapper = new ObjectMapper();
File file = new File("artist.json");
try {
//序列化Java对象信息JSON文件。
mapper.writeValue(file, artist);
} catch (IOException e) {
e.printStackTrace();
}
try {
//将JSON文件反序列化为Java对象。
Artist newArtist = mapper.readValue(file, Artist.class);
System.out.println("newArtist.getId() = " + newArtist.getId());
System.out.println("newArtist.getName() = " + newArtist.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}代码段的结果是:
newArtist.getId() = 1 newArtist.getName() = The Beatles
Maven依赖
<!-- http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.8.6/jackson-databind-2.8.6.jar -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>