休息模板Jackson-自定义JSON反序列化? [英] RestTemplate & Jackson - Custom JSON deserializing?

查看:151
本文介绍了休息模板Jackson-自定义JSON反序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Web服务返回一个空字符串而不是NULL,这将导致Jackson崩溃. 因此,我创建了一个自定义解析器,并尝试手动解析它?知道我该如何实现吗?

The webservice returns an empty string instead of NULL which causes Jackson to crash. So I created a custom parser, and I'm trying to parse it manually? Any idea How I could achieve this?

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

What Am I doing wrong here? All I'm trying to do is to parse JSON to object as I normally would. The field names are added to my properties using @JsonProperty so the parser should know how to convert it.

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;
    }

}

推荐答案

这是我的解决方法

@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;
}

这篇关于休息模板Jackson-自定义JSON反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆