简体   繁体   English

Jackson Objectmapper将空字符串反序列化为“ null”值

[英]Jackson objectmapper deserializing null string to “null” value

Sometimes during deserialization the null is getting converted to "null". 有时在反序列化期间,null会转换为“ null”。 Is there a way I can avoid this? 有办法避免这种情况吗?

{
    "item" : {
        "title": "null",
        "id" : "134df"
    }
}

I want it as 我想要它

{
    "item" : {
        "title": null,
        "id" : "134df"
    }
}

or 要么

{
    "item" : {
        "title": "",
        "id": "134df"
    }
}

You can achieve it by using Google JSON ie gson. 您可以使用Google JSON即gson来实现。

If you are setting null against the title, then while converting the Object to JSON at that time title will not be available in the JSON string. 如果您将标题设置为null,则在那时将Object转换为JSON时,JSON字符串中将不提供标题。 After that you can check a condition whether the object is available or not in the JSON and do the further task. 之后,您可以检查条件JSON中对象是否可用,并执行其他任务。

Here is the code spinet. 这是代码清单。

import com.google.gson.Gson;

public class JackSonObjectMapperExample {

    public static void main(String[] args){
        Item item = new Item();

        item.setId("134df");
        item.setTitle(null);

        POJOExample pojo = new POJOExample();
        pojo.setItem(item);

        Gson gson = new Gson();
        String jsonInString = gson.toJson(pojo);

        System.out.println("=================>>"+jsonInString);
    }
}

class POJOExample{
    private Item item;
    public Item getItem() {
        return item;
    }
    public void setItem(Item item) {
        this.item = item;
    }
}

class Item{
    private String title;
    private String id;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}

output: =================>>{"item":{"id":"134df"}} 输出:================ >> {“ item”:{“ id”:“ 134df”}}

Hope, this will help you. 希望这个能对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM