代码之家  ›  专栏  ›  技术社区  ›  Ori Marko

对象映射器-如何在JSON中发送空值

  •  1
  • Ori Marko  · 技术社区  · 6 年前

    根据第三方API规范,我需要在json中使用 ObjectMapper 如果不存在值,

    预期结果: "optional": null

    如果存在可选值,则发送 "optional": "value"

    我没有找到这样的选择 Jackson – Working with Maps and nulls

    代码:

    requestVO = new RequestVO(optional);
    ObjectMapper mapper = new ObjectMapper();
    String requestString = mapper.writeValueAsString(requestVO);
    

    班级:

    public class RequestVO {
       String optional;
       public RequestVO(String optional) {
          this.optional = optional;
       }
    
    public String getOptional() {
        return optional;
    }
    
    public void setOptional(String optional) {
        this.optional= optional;
    }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Emre Savcı    6 年前

    添加 @JsonInclude(JsonInclude.Include.USE_DEFAULTS) 类的注释。

    @JsonInclude(JsonInclude.Include.USE_DEFAULTS)
    class RequestVO {
        String optional;
    
        public RequestVO(String optional) {
            this.optional = optional;
        }
    
        public String getOptional() {
            return optional;
        }
    
        public void setOptional(String optional) {
            this.optional = optional;
        }
    }
    

    例子:

    RequestVO requestVO = new RequestVO(null);
    
    ObjectMapper mapper = new ObjectMapper();
    try {
        String requestString = mapper.writeValueAsString(requestVO);
        System.out.println(requestString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    

    输出:

    {"optional":null}
    

    具有价值:

    RequestVO requestVO = new RequestVO("test");
    
    ObjectMapper mapper = new ObjectMapper();
    try {
        String requestString = mapper.writeValueAsString(requestVO);
        System.out.println(requestString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    

    输出:

    {"optional":"test"}
    

    你可以用 @JsonInclude 偶数属性上的批注。因此,通过这种方式,可以序列化为空,或者在序列化时忽略一些属性。

        2
  •  1
  •   Táizel Girão Martins    6 年前

    您可以这样配置对象映射器:

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    

    如果JSON请求中没有任何值,则处理后的 null 如你所料。

    您甚至可以配置 Spring 豆豆 ObjectMapper 如果你需要的话。

    编辑:

    我误解了这个问题,他对JSON响应感兴趣,而不是对解析的对象感兴趣。 正确的属性是 JsonInclude.Include.USE_DEFAULTS .

    为困惑道歉。