RestTemplate&杰克逊 - 自定义JSON反序列化?

时间:2013-02-03 23:50:52

标签: java json jackson resttemplate

webservice返回一个空字符串而不是NULL,这会导致Jackson崩溃。 所以我创建了一个自定义解析器,我试图手动解析它?任何想法我怎么能做到这一点?

我在这里做错了什么?我所要做的就是像往常一样将JSON解析为对象。使用@JsonProperty将字段名称添加到我的属性中,以便解析器应该知道如何转换它。

public class InsertReplyDeserializer extends JsonDeserializer<ListingReply> {

    @Override
    public ListingReply deserialize(JsonParser jsonParser, DeserializationContext arg1)
            throws IOException, JsonProcessingException {

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);

        // If service returns "" instead of null return a NULL object and don't try to parse
        if (node.getValueAsText() == "")
            return null;


       ObjectMapper objectMapper = new ObjectMapper();
       ListingReply listingReply = objectMapper.readValue(node, ListingReply.class);


       return listingReply;
    }

}

2 个答案:

答案 0 :(得分:0)

以下是我如何解决它

@Override
public MyObject deserialize(JsonParser jsonParser, DeserializationContext arg1)
        throws IOException, JsonProcessingException {

    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);

    if (node.getValueAsText() == "")
        return null;

    MyObject myObject = new MyObject();
    myObject.setMyStirng(node.get("myString").getTextValue());

    JsonNode childNode = node.get("childObject");
    ObjectMapper objectMapper = new ObjectMapper();
    ChildObject childObject = objectMapper.readValue(childNode,
            ChildObject.class);

             myObject.setChildObject(childObject);
             return myObject;
}

答案 1 :(得分:0)

我不确定您是否需要手动解析响应。你的解决方案可行,但在我看来似乎不是最优的。由于看起来您正在使用RestTemplate,因此您应该编写(或将解析器代码移动到)您自己的消息转换器。然后将此转换器添加到您的rest模板对象,该对象将在内部反序列化您的值。一些事情,

public class CustomHttpmsgConverter extends  AbstractHttpMessageConverter<Object> {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
   InputStream istream = inputMessage.getBody();
   String responseString = IOUtils.toString(istream);
   if(responseString.isEmpty()) //if your response is empty
     return null;
   JavaType javaType = getJavaType(clazz);
   try {
       return this.objectMapper.readValue(responseString, javaType);
   } catch (Exception ex) {
    throw new HttpMessageNotReadableException(responseString);
    }
}

//add this converter to your resttemplate
    RestTemplate template = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new CustomHttpmsgConverter());
    template.setMessageConverters(converters);