gpt4 book ai didi

java - Jackson JSON 不包装嵌套对象的属性

转载 作者:IT老高 更新时间:2023-10-28 13:50:01 26 4
gpt4 key购买 nike

我有以下类(class):

public class Container {
private String name;
private Data data;
}

public class Data {
private Long id;
}

当我序列化 Container我得到的使用 Jackson 的类(class)

{"name":"Some name","data":{"id":1}}

但我需要的结果是:

{"name":"Some name","id":1}

有可能吗(不添加Container.getDataId() 方法)?如果有,该怎么做?


更新

我尝试创建自定义 JsonSerializer<Data>但结果和以前一样

public class JsonDataSerializer extends JsonSerializer<Data> {

private static Logger logger = Logger.getLogger(JsonDataSerializer.class);

@Override
public void serialize(Data value, JsonGenerator jgen,
SerializerProvider provider)
throws IOException,JsonProcessingException {

Long id = (value.getId() == null) ? 0l : value.getId();
jgen.writeStartObject();
jgen.writeNumberField("id", id);
jgen.writeEndObject();
logger.debug("Data id " + id + " serialized to JSON.");
}
}

我也尝试添加 @JsonSerialize上面的注释Data类,然后在 Container 中高于 getter类(class)。正如我之前提到的,没有任何成功。使用了我的序列化程序,logger 记录消息。


更新 2

当我删除 writeStartObject()writeEndObject()则不返回 JSON,仅返回 HTTP Status 500错误,除了我在调试输出中发现的内容之外没有抛出异常。

DEBUG: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.example.DataController@16be8a0]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name, expecting a value; nested exception is org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value
DEBUG: org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [com.example.DataController@16be8a0]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name, expecting a value; nested exception is org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value
DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [com.example.DataController@16be8a0]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not write a field name, expecting a value; nested exception is org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value

最佳答案

Jackson 1.9 引入了 JsonUnwrapped注释可以满足您的需求。

关于java - Jackson JSON 不包装嵌套对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6983067/

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