我正在使用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,有时代码为null,我不想显示它。
答案 0 :(得分:2)
使用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;
}
}