【问题标题】:How not to display null values in json as response from jax-rs如何不在 json 中显示空值作为来自 jax-rs 的响应
【发布时间】:2013-09-24 10:00:47
【问题描述】:

我正在使用 jax rs,我想将响应创建为 json,代码:

@Produces(MediaType.APPLICATION_JSON)
public class Rest{
@GET
Path("/Test")
public RestResponse restTest(){
return new RestResponse(100,"ERROR");
}
}

@XmlRootElement()
public class RestResponse{
private Integer code;
private String status;
private Integer id;

public RestResponse(Integer code, String status){
this.code = code;
this.status = status;
}
}

我收到的回复是:
{"status":"ERROR","code":100,"id":null}

如何删除 "id":null 值? 我想对外观做出回应: {"status":"ERROR","code":100}

我需要它,因为有时 id 为 null,有时 code 为 null,我不想显示它。

【问题讨论】:

    标签: java json rest jax-rs


    【解决方案1】:

    使用Genson,您可以这样做:

    // register a provider for your custom genson configuration.
    @Provider
    public class GensonCustomResolver implements ContextResolver<Genson> {
      // configure the Genson instance
      private final Genson genson = new Genson.Builder()
                                            // if you want to support JAXB annotations
                                            .with(new JAXBBundle())
                                            .setSkipNull(true)
                                            .create();
    
      @Override
      public Genson getContext(Class<?> type) {
        return genson;
      }
    }
    

    【讨论】:

    • omg 如此简单而强大,再次感谢它让我的生活更轻松
    猜你喜欢
    • 2019-05-06
    • 2017-04-29
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2014-12-27
    • 2020-05-07
    相关资源
    最近更新 更多