@JsonValue

@JsonValue indicates a single method that should be used to serialize the entire insance.

For example in an enum - we annotate the getName with @JsonValue so that any such entity is serialized via its name:

public enum TypeEnumWithValue {
    TYPE1(1, "Type A"),
    TYPE2(2, "Type 2"),
    TYPE3(3, "Type 3"),
    ;

    private Integer id;

    private String name;

    TypeEnumWithValue(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

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

    public void setName(String name) {
        this.name = name;
    }
}

我们的测试:

@Test
public void test04() throws Exception {
    String s = mapper.writeValueAsString(TypeEnumWithValue.TYPE1);
    System.out.println(s);
    Assert.assertThat(s, CoreMatchers.is("\"Type A\""));
}

results matching ""

    No results matching ""