如何忽略Jersey Rest中JSON对象的属性编辑

时间:2015-11-23 06:58:53

标签: java rest

作为我的要求的一部分,我公开了一个Web服务,该服务将Employee类作为JSON格式的输入。员工类如下。如果您看到类中有3个属性,如status,password,creationTime。现在我试图阻止用户提供status和creationTime等属性。我的意思是说我不想让用户输入JSON: -

{
  "emp_id": "xyz@gmail.com",
  "credentials" : {"password": "xxxxx"},
  "status": "ACTIVE",
  "creationTime": "<UTC time>"
}

当输入status和creationTime时,它将导致400错误消息。同样,当我向用户显示类似return Response.status(Status.ACCEPTED).entity(employee).build();之类的结果时,它不应显示creationTime或凭据。它应该看起来像: -

 {
      "emp_id": "xyz@gmail.com",
      "status": "ACTIVE",
    }

我可以看到有一个@JsonIgnore属性在我的情况下不适用于状态。我试过杰克逊。

我的员工课程如下:

import java.util.Date;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;

@XmlRootElement
public class Employee {
    @XmlElement(name = "emp_id", required = true)
    @JsonProperty("emp_id")
    private String empId;
    private Credentials credentials;
    private String status;
    private Date creationTime;

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public Credentials getCredentials() {
        return credentials;
    }

    public void setCredentials(Credentials credentials) {
        this.credentials = credentials;
    }

    @JsonIgnore
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Date getCreationTime() {
        return creationTime;
    }

    public void setCreationTime(Date creationTime) {
        this.creationTime = creationTime;
    }

}

5 个答案:

答案 0 :(得分:1)

Jersey默认JSON提供程序

来自Jersey documentation

  

通过MOXy的JSON绑定支持是自Jersey 2.0以来在Jersey应用程序中支持JSON绑定的默认和首选方式。当JSON MOXy模块位于类路径上时,Jersey将自动发现模块并通过MOXy在应用程序中无缝启用JSON绑定支持。

由于MOXy支持JAXB annotations,请尝试使用@XmlTransient。应该这样做。

使用Jackson作为JSON提供者

要将Jackson 2.x用作JSON提供程序,您需要将jersey-media-json-jackson模块添加到pom.xml文件中:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.22.1</version>
</dependency>

要使用Jackson 1.x,您需要jersey-media-json-jackson1模块:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson1</artifactId>
    <version>2.22.1</version>
</dependency>

有关依赖关系的更多信息,请查看Jersey documentation

如果可以的话,选择Jackson 2.x而不是Jackson 1.x。

将杰克逊注册为JSON提供商

为了使用杰克逊作为您的JSON提供者,您需要在JacksonFeature课程中为杰克逊2.x(或杰克逊1.x的Jackson1Feature)注册ResourceConfig(泽西&# 39;自己实现Application类):

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        register(JacksonFeature.class);
    }
}

有关详细信息,请查看documentation

选择正确的JsonProperty注释

确保根据Jackson版本使用正确的JsonProperty注释:

有关注释的更多详细信息,请查看文档:

尝试注释你的字段

此外,请尝试使用正确的getStatus()注释注释status字段,而不是注释@JsonProperty方法。

答案 1 :(得分:0)

每当您的其他Web服务将使用此json对象时,它都会将其转换为POJO对象。如果您的JSON对象不包含POJO对象中的某些字段,那么这些值将初始化为NULL。

现在,您可以通过检查空值来相应地给出404响应。

答案 2 :(得分:0)

首先,检查您正在使用的Json / XML解析器。泽西默认为Moxy,所以将Moxy替换为杰克逊作为@JsonIgnore使用的是Jackson注释。

添加以下依赖项以启用Json和XML的Jackson解析器。

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.5.4</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-xml-provider</artifactId>
    <version>2.5.4</version>
</dependency>

泽西岛有自动发现机制,应该自动注册杰克逊,如果失败,请使用下面的类。

public class ResourceConfig extends org.glassfish.jersey.server.ResourceConfig {

    public ResourceConfig() {
    super();
    registerJacksonProvider();
    packages("com.rest");
    }

    /**
     * Custom provider to handle JSON and XML request
     */
    private void registerJacksonProvider() {
    ObjectMapper mapper = new ObjectMapper();
    XmlMapper xmlMapper = new XmlMapper();

    xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    JacksonJaxbXMLProvider xmlProvider = new JacksonJaxbXMLProvider();

    provider.setMapper(mapper);
    xmlProvider.setMapper(xmlMapper);

    register(provider);
    register(xmlProvider);
    }

}

要停用Moxy,请添加以下类。

import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.CommonProperties;
import org.glassfish.jersey.server.ServerProperties;

@Provider
public class DisableMoxyFeature implements Feature {
    @Override
    public boolean configure(final FeatureContext context) {
    final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE + '.'
        + context.getConfiguration().getRuntimeType().name().toLowerCase();
    context.property(disableMoxy, true);
    context.property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true);
    context.property(ServerProperties.MOXY_JSON_FEATURE_DISABLE, true);
    return true;
    }
}

答案 3 :(得分:0)

使用JSON-Lib从employee对象构建json响应对象时,可以传递可以排除特定属性的jsonconfig,也可以将json属性过滤器设置为该配置,如下所示

swagger: "2.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
  termsOfService: http://helloreverb.com/terms/
  contact:
    name: Wordnik API Team
    email: foo@example.com
    url: http://madskristensen.net
  license:
    name: MIT
    url: http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
host: petstore.swagger.wordnik.com
basePath: /api
schemes:
  - http
consumes:
  - application/json
produces:
  - application/json
paths:
  /pets:
    get:
      description: |
        Returns all pets from the system that the user has access to
        Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
        Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
      operationId: findPets
      parameters:
        - $ref: '#/parameters/tagsParam'
        - $ref: '#/parameters/limitsParam'


parameters:
  tagsParam:
    name: tags
    in: query
    description: tags to filter by
    required: false
    type: array
    collectionFormat: csv
    items:
      type: string
  limitsParam:
    name: limit
    in: query
    description: maximum number of results to return
    required: false
    type: integer
    format: int32

OR

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
  public boolean apply(Object source, String name, Object value) {
    if ("credentials".equals(name) || "creationTime".equals(name)) {
      return true;
    }
    return false;
  }
});

对于问题的第一部分,您可以很好地使用json模式并在处理之前验证收到的json对象

JsonConfig config = new JsonConfig();
List<String> excludes = new ArrayList<String>();
excludes.add("credentials");
excludes.add("creationTime");

JSONObject.fromObject(response, jsonConfig);

答案 4 :(得分:0)

使用 @JsonbTransient 代替 @JsonIgnore