2

我正在使用 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 为空,有时代码为空,我不想显示它。

4

1 回答 1

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;
  }
}
于 2013-09-24T10:42:01.840 回答