jackson-databindを導入 (maven)
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.3</version>
</dependency>
enumを定義
import com.fasterxml.jackson.annotation.JsonProperty;
public enum Status {
@JsonProperty("finished")
DONE,
@JsonProperty("wip")
IN_PROGRESS,
@JsonProperty("ready")
NOT_STARTED;
}
JSONモデルを定義
public class Task {
public String title;
// enum
public Status status;
}
メソッドをpublicにしないとdeserialize時にエラーが出るので注意。
デシリアライズ
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonApp {
public static void main(String[] args) {
String taskString = "{\"title\": \"do something\", \"status\": \"finished\"}";
try {
Task task = new ObjectMapper().readValue(taskString, Task.class);
System.out.println("title: " + task.title);
System.out.println("status: " + task.status);
} catch (JsonProcessingException e) {
System.out.println("error: " + e.getMessage());
}
}
}
結果
title: do something
status: DONE