gpt4 book ai didi

java - 使用 Jackson 反序列化任意 JSON

转载 作者:行者123 更新时间:2023-11-30 09:00:31 27 4
gpt4 key购买 nike

我有一个 JSON clob,我正在将其反序列化为一个 bean,然后将其作为 JSON 作为 HTTP 请求的响应发送。

我想向包含任意 JSON 的 bean 添加一个 JSONObject 字段。

这是我的 bean :

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DTO implements Serializable {
private String height;
private String width;
//I would like to add this field
//private JSONObject settings;

下面是我如何反序列化 CLOB:

DTO layout = null;
String json = "{\"height\": \"300px\", \"width\": \"100%\"}";
final ObjectMapper mapper = jackson.getContext(DTO.class);

try {
layout = mapper.readValue(json, DTO.class);
}
catch(IOException ex) {
logger.error("Unable to deserialize Dashboard layout CLOB", ex);
}

这行得通。但是,我需要我的 clob 包含一个包含任意 JSON 的设置对象。这可能吗?例如:

 {"height": "300px", "width": "100%", "settings": {"propA": 1, "propB": "red"}}

当我尝试使用 JSONObject 时,出现错误:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.codehaus.jettison.json.JSONObject and no properties discovered to create BeanSerializer (to avoid  exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain:  api.jaxb.DTO["settings"])

最佳答案

JSONObject 来自 JSON library这是一个独立于 jackson 的包裹。在您的情况下,您应该使用 JsonNode来自 jackson 图书馆。:

public class DTO implements Serializable {
...
private org.codehaus.jackson.JsonNode settings;

关于java - 使用 Jackson 反序列化任意 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26767769/

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