我需要为休息服务显示以下类型的Json响应:
{
"Server up": false,
"database running": true,
"dependency 1 up": true
}
为此,我定义了Java对象HealthCheckResponse.java,它有一个map字段。
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;
}}
但是当我打印最终答案时,它也会出现在地图字段的名称中。
{
"statusMap":
{
"Server up": false,
"database running": true,
"dependency 1 up": true
}
}
请建议我需要在HealthCheckResponse.java中进行更改,以摆脱&#34; statusMap&#34;和输出显示中的额外花括号。 这是我正在使用的对象映射器:
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());
}
}
答案 0 :(得分:1)
我相信@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));
并且输出将是:
{&#34; Server up&#34;:false,&#34;数据库正在运行&#34;:true,&#34;依赖1 up&#34;:true}
答案 1 :(得分:1)
您应该使用@JsonValue和@JsonAnySetter批注:
public class HealthCheckResponse {
private Map<String, Boolean> statusMap = new HashMap<>();
@JsonValue
public Map<String, Boolean> getStatusMap() {
return statusMap;
}
@JsonAnySetter
public void add(String key, Boolean value) {
statusMap.put(key, value);
}
}
并使用:
ObjectMapper objectMapper = new ObjectMapper();
HealthCheckResponse healthCheckResponse = new HealthCheckResponse();
healthCheckResponse.add("Server up", false);
healthCheckResponse.add("database running", true);
healthCheckResponse.add("dependency 1 up", true);
String json = objectMapper.writeValueAsString(healthCheckResponse);
System.out.println(json);
HealthCheckResponse object = objectMapper.readerFor(HealthCheckResponse.class).readValue(json);
System.out.println(object.getStatusMap());