gpt4 book ai didi

java - 使用 Jackson 将 map 序列化为 json 而不在输出中显示 map 名称

转载 作者:行者123 更新时间:2023-11-29 07:43:19 32 4
gpt4 key购买 nike

我需要为休息服务显示以下类型的 Json 响应:

{
"Server up": false,
"database running": true,
"dependency 1 up": true
}

为此,我定义了具有映射字段的 Java 对象 HealthCheckResponse.java。

public class HealthCheckResponse {
@JsonProperty
private Map<String, Boolean> statusMap;

public Map<String, Boolean> getStatusMap() {
return statusMap;
}
public void setStatusMap(Map<String, Boolean> statusMap) {
statusMap = statusMap;
}}

但是当我打印最终响应时, map 字段的名称也会出现在其中。

{
"statusMap":
{
"Server up": false,
"database running": true,
"dependency 1 up": true
}
}

请建议我需要在 HealthCheckResponse.java 中进行哪些更改,以摆脱输出显示中的“statusMap”和多余的花括号。这是我正在使用的对象映射器:

public class CustomObjectMapper extends ObjectMapper {

public CustomObjectMapper() {
super();

configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

setVisibilityChecker(getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE).withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE).withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));

setSerializationInclusion(Include.NON_NULL);

registerModule(new StringModule());
registerModule(new GuavaModule());
}
}

最佳答案

我相信 @JsonValue 在这里可以提供帮助。如果您更改对以下内容的回复:

public class HealthCheckResponse {
private Map<String, Boolean> statusMap;

@JsonValue
public Map<String, Boolean> getStatusMap() {
return statusMap;
}

public void setStatusMap(Map<String, Boolean> statusMap) {
this.statusMap = statusMap;
}
}

// The mapper can be used like this
final ObjectMapper mapper = new ObjectMapper();

// The POJO
final HealthCheckResponse healthCheckResponse = new HealthCheckResponse();
final Map<String, Boolean> statusMap = new HashMap<>();
statusMap.put("Server up", false);
statusMap.put("database running", true);
statusMap.put("dependency 1 up", true);
healthCheckResponse.setStatusMap(statusMap);

System.out.println(mapper.writeValueAsString(healthCheckResponse));

并且,输出将是:

{"Server up":false,"database running":true,"dependency 1 up":true}

关于java - 使用 Jackson 将 map 序列化为 json 而不在输出中显示 map 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27977437/

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