0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

jackson-databindでStringをenum型にデシリアライズする

Last updated at Posted at 2024-09-24

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?