我有Spring Boot Application返回对象的响应。我的响应对象的结构如下:
AddtlParams {
AdtlParam列表
}
AdtlParam {
String key
List<String> values
}
我需要使用XML注释在JSON中进行以下响应
AddtlParams:{
param1:[pama1-value],
param2:[pama2-value],
。
paramn:[parman-value],
}
XML正确返回,但JSON格式包含AdtlParams列表标记。如何避免这种情况并获得上述格式的JSON响应
答案 0 :(得分:0)
类AdditionalParamsSerializer扩展了JsonSerializer {
String sValue = "";
@Override
public void serialize(List<AdditionalParam> lstApms, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
gen.writeStartObject();
for (int i = 0; i < lstApms.size(); ++i) {
AdditionalParam ap = lstApms.get(i);
serialize(ap, gen);
}
gen.writeEndObject();
}
private void serialize(AdditionalParam ap, JsonGenerator gen) throws IOException {
gen.writeFieldName(ap.getName());
gen.writeStartArray();
if ((null != ap.getValue()) && (!ap.getValue().toString().trim().equalsIgnoreCase(""))) {
sValue = ap.getValue();
}
if ((null != ap.getValues()) && (!ap.getValues().toString().trim().equalsIgnoreCase(""))) {
sValue = ap.getValues().stream().map(n -> String.valueOf(n)).collect(Collectors.joining("|"));
}
if (!sValue.equalsIgnoreCase(""))
gen.writeString(sValue);
else {
gen.writeStartObject();
gen.writeEndObject();
}
gen.writeEndArray();
sValue = "";
}
}