2014-11-05 44 views
2

我有一個JSON clob,我反序列化成一個bean,然後作爲JSON作爲HTTP請求的響應發送。反序列化與傑克遜的任意JSON

我想添加一個JSONObject字段到包含任意JSON的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"]) 
+0

你需要有領域反序列化到你的對象,或者您可以忽略它們? – mkobit 2014-11-06 07:34:58

+1

你的'settings'對象應該是Jackson的一部分'JsonNode',然後你的反序列化應該可以正常工作。 – mkobit 2014-11-06 08:19:11

+0

@MikeKobit這個作品!如果你想發佈這個作爲答案,我會接受它。謝謝 – ryansilva 2014-11-06 13:57:20

回答

2

JSONObject來自JSON library這是一個獨立的包比傑克遜。在你的情況,你應該使用JsonNode從傑克遜庫:

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