Jackson: enum instance methods to return values as strings

北城余情 提交于 2020-01-17 13:04:15

问题


Please note: Although this question seems similar to this one I am asking a slightly different question.

I am serializing/deserializing POJOs into JSON via Jackson.

I am trying to get instances of my UserStatus enum to (de)serialize nicely and am attempting via:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
enum UserStatus {
    Unregistered,
    Activated,
    Deactivated,
    Locked

    @JsonValue
    String toValue() {
        // TODO: ???
    }
}

If my understanding of Jackson is correct, then my toValue() method just need to figure out what value the current UserStatus instance is, and convert it to a String. So UserStatus.Activated.toValue() should gives us a String with a value of "Activated".

Main question: How do I accomplish this?

Ancillary question: Is this the right way to serialize/deserialize enums in Jackson-land?


回答1:


Just invoke name() method. See below example:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

;

public class JacksonTest {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);

        Pojo pojo = new Pojo();
        pojo.userStatus = UserStatus.Activated;
        String json = mapper.writeValueAsString(pojo);
        System.out.println(json);
        Pojo deserializedPojo = mapper.readValue(json, Pojo.class);
        System.out.println("--");
        System.out.println(deserializedPojo);
    }

    public static class Pojo {
        public UserStatus userStatus;

        @Override
        public String toString() {
            return userStatus.name();
        }
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public enum UserStatus {
        Unregistered, Activated, Deactivated, Locked;

        @JsonValue
        public String toValue() {
            return name();
        }
    }
}

Above program prints:

{
  "userStatus" : "Activated"
}
--
Activated



回答2:


Starting with Jackson 2.1.2 you can use the @JsonFormat annotation to control how Enum instances are serialized into JSON strings.

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Type { ... }

See http://www.baeldung.com/jackson-serialize-enums



来源:https://stackoverflow.com/questions/27049465/jackson-enum-instance-methods-to-return-values-as-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!