有没有办法像@JsonFilter那样只打印HashMap的值?

时间:2020-02-05 21:43:45

标签: java json jackson

我希望我的地图仅在序列化为JSON时才打印值。该过滤器中用于格式化日期的内容

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
LocalDate startDate;

1 个答案:

答案 0 :(得分:1)

假设您有一个将Map作为字段的对象,并且想要序列化该对象,但是您想只打印列表中的值,而不是map属性的键值对,可以为此转换添加一个自定义的getter:

public class MyTest {

    private Map<String, Object> myMapProperty = new HashMap<>();

    @JsonIgnore
    public Map<String, Object> getMyMapProperty() {
        return myMapProperty;
    }

    public void setMyMapProperty(final Map<String, Object> myMapProperty) {
        this.myMapProperty = myMapProperty;
    }

    @JsonProperty("myMapProperty")
    public List<Object> getMyMapPropertyValues() {
        return myMapProperty.values()
                .stream() // use .map to transform values, e.g. flatten if values are Lists themselves
                .collect(Collectors.toList());
    }

    @Test
    public void test() throws JsonProcessingException {
        final MyTest myObject = new MyTest();
        myObject.getMyMapProperty().put("k1", "value1");
        myObject.getMyMapProperty().put("k2", "value2");

        final String value = new ObjectMapper().writeValueAsString(myObject);
        System.out.println(value);
    }

}