将空值从Java bean转换为JSON

时间:2018-06-07 15:22:17

标签: java json javabeans isnullorempty

我的流程如下。

enter image description here 我的问题是什么:

输入json请求将某些字段设置为“”。我希望响应json将这些字段设置为“”。 相反,字段的值为null或0。

我需要什么: 如何设置字段以响应“”而不是null或0?

代码:

JSON请求:

    {
    userID: "ABC",
    creationDate: "",
    noOfItems: "" 
}

Bean定义:

class UserOrderDetails {
    private String userID;
    private LocalDate creationDate;
    private int noOfItems;

    public String getUserID() {
        return this.userID;
    }

    public void setUserID(String userID) {
        this.userID=userID;
    }
    public LocalDate getCreationDate() {
        return this.creationDate;
    }

    public void setCreationDate(LocalDate creationDate) {
        this.creationDate=userID;
    }   
    public int getNoOfItems() {
        return this.noOfItems;
    }

    public void setNoOfItems(int noOfItems) {
        this.noOfItems=noOfItems;
    }
}

控制器类:

class UserOrderCreationController {
@RequestMapping(value = "/createUserOrder", method = RequestMethod.POST)
    public ResponseEntity<?> createUserOrder(@RequestBody UserOrderDetails userOrderDetails , @RequestHeader HttpHeaders headers) throws Exception{
    //Some business logic to handle the user Order
    return new ResponseEntity<UserOrderDetails>(userOrderDetails, HttpStatus.CREATED);
    }
}

响应:

{
    userID: "ABC",
    creationDate: null,
    noOfItems: 0 
}

注意:我无法将LocalDate,int - CreationDate和noOfItems的数据类型更改为String,因为它被许多其他类使用。

1 个答案:

答案 0 :(得分:1)

对于String字段,无论您发送的值是什么,将保存并将返回给其他数据类型,如DATE,Integer,如果值为Balnk,则将JSON值转换为JAVA(&#34; &#34;)/ null,对象映射器将其转换为null并保存到DB,同样将在响应中返回。 如果你想要null作为&#34;&#34;作为回应,您应该编写customSerializer,它将null转换为&#34;&#34;作为回应。 您需要使用
为这些字段添加注释  @JsonSerialize(using = ToStringSerializer.class)

ToStringSerializer.class我们需要写。

解决方法:     我有这个解决方法,你可以尝试看看吗。

公共类AssignNullSerializer2扩展了JsonSerializer {

public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException
{
    // any JSON value you want...
    if(value==null) {
    jgen.writeString("");
    }
}

} 在ApplicationConfiguration中添加以下代码段。

    ObjectMapper mapper = new ObjectMapper();
DefaultSerializerProvider sp=new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new AssignNullSerializer2());
mapper.setSerializerProvider(sp);

它会将DTO&#39; S /响应对象中的所有空值转换为&#34;&#34; / Empty_String 我找不到将其应用于特定领域的控制权。