有时在反序列化过程中,null 会转换为“null”。有什么办法可以避免这种情况吗?
{
"item" : {
"title": "null",
"id" : "134df"
}
}
我想要它作为
{
"item" : {
"title": null,
"id" : "134df"
}
}
或
{
"item" : {
"title": "",
"id": "134df"
}
}
最佳答案
您可以使用 Google JSON 即 gson 来实现它。
如果您将标题设置为 null,则在将对象转换为 JSON 时,标题将在 JSON 字符串中不可用。 之后,您可以检查 JSON 中对象是否可用的条件并执行进一步的任务。
这是代码 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;
}
}
输出: =================>>{"item":{"id":"134df"}}
希望这会对您有所帮助。
关于java - Jackson objectmapper 将空字符串反序列化为 "null"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39569683/