gpt4 book ai didi

java - 有没有一种方法,例如使用 @JsonFilter 来仅打印 HashMap 的值?

转载 作者:行者123 更新时间:2023-12-02 09:02:08 26 4
gpt4 key购买 nike

我希望我的 map 仅在序列化为 JSON 时打印值。类似于此过滤器的内容,用于格式化日期

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

最佳答案

假设您有一个以 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);
}

}

关于java - 有没有一种方法,例如使用 @JsonFilter 来仅打印 HashMap 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60084555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com