在编组之前动态隐藏一些字段(java到json)

在编组之前动态隐藏一些字段(java到json),java,java-8,jackson,jax-rs,swagger,Java,Java 8,Jackson,Jax Rs,Swagger,我有一个jax rs端点,它应该返回一个JSON对象,但我想选择一些字段并隐藏一些其他字段,我的代码如下: import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import org.apach

我有一个jax rs端点,它应该返回一个JSON对象,但我想选择一些字段并隐藏一些其他字段,我的代码如下:

import javax.ws.rs.BadRequestException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Component
@Path("/customers")
@Api(value = "Customers resource", produces = MediaType.APPLICATION_JSON_VALUE)
public class CustomersEndpoint{
    private final CustomersService customersService;

    public CustomersEndpoint(CustomersService customersService) {
        this.customersService = customersService;
    }
@GET
    @Path("{customerResourceId}")
    @Produces(MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "Get customer details")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Listing the customer details", response = **Customer**.class)") })
    public **Customer** getCustomerDetails(@ApiParam(value = "ID of customer to fetch") @PathParam("customerResourceId") String customerId,
                                      @QueryParam(value = "Retrieve only selected fields [by comma]") String fields )
            throws ApiException {       

        return this.customersService.getCustomerDetails(customerId,fields);
    }
我在这里的例子是,我只想为所选字段返回一个自定义“Customer

我使用jax-rs、jackson将/marshall对象解组为JSON

有什么解决办法吗

客户类的示例:

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Customer {

        public Customer() {

            }

    public Customer(String customerId,String phoneNumber) {

        this.customerId=customerId;
        this.phoneNumber=phoneNumber;
    }

    /**
     * customer identifier
     */
    @JsonPropertyDescription("customer identifier")
    @JsonProperty("customerId")
    private String customerId;

    /**
     * customer phone number
     */
    @JsonPropertyDescription("customer phone number")
    @JsonProperty("phoneNumber")
    private String phoneNumber;
    /**
     * customer first number
     */
    @JsonPropertyDescription("customer first number")
    @JsonProperty("firstName")
    private String firstName;
    /**
     * customer last number
     */
    @JsonPropertyDescription("customer last number")
    @JsonProperty("lastName")
    private String lastName;
public String getCustomerId() {
        return customerId;
    }
    public Customer setCustomerId(String customerId) {
        this.customerId = customerId;
        return this;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }
    public Customer setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
        return this;
    }
    public String getFirstName() {
        return firstName;
    }
    public Customer setFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }
    public String getLastName() {
        return lastName;
    }
    public Customer setLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }
}
输出:

{
  "customerId": "string",
  "phoneNumber": "string",
  "firstName": "string",
  "lastName": "string",
}
=>选择后的结果:字段=电话号码,客户ID

{
  "customerId": "string",
  "phoneNumber": "string"
}

我知道什么时候实例化对象,不设置“隐藏”属性,并包含此注释@JsonInclude(JsonInclude.include.NON_NULL)将是一个解决方案,但它需要太多的代码和维护。

有几种不同的方法指示jackson不要序列化属性。其中之一是在正在序列化的java类中注释ignore属性。在下面的示例中,intValue不会在json中序列化

private String stringValue;

@JsonIgnore
private int intValue;

private boolean booleanValue;
下面是一篇很好的文章,介绍了忽略json序列化字段的其他策略


我认为您应该向该过滤器添加一个组件:

@Component
public class CustomerFilterConfig {


    public static  Set<String> fieldNames = new HashSet<String>();

      @Bean
      public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider().setFailOnUnknownId(false);
        FilterProvider filters =simpleFilterProvider.setDefaultFilter(SimpleBeanPropertyFilter.filterOutAllExcept(fieldNames)).addFilter("customerFilter", SimpleBeanPropertyFilter.filterOutAllExcept(fieldNames));    
        objectMapper.setFilterProvider(filters);
        return objectMapper;
      } 


}
最后,要使用该过滤器:

String fields = "A,B,C,D";
CustomerFilterConfig.fieldNames.clear();
CustomerFilterConfig.fieldNames.addAll(Arrays.asList(fields.split(",")));

向我们展示您在
Customer
上使用的Jackson注释。Done@intentiallyleftblank,我已经添加了所需的代码我确实确认了,但我如何动态执行呢!实例化对象之后!你是说你的忽略字段在运行时是有条件的吗?我从来没有使用过它,但是做了一些搜索,看起来设置@JsonFilter会给你想要的。你必须仔细阅读它,看看如何全面实施它。它似乎可以完全控制在运行时序列化哪些属性。
String fields = "A,B,C,D";
CustomerFilterConfig.fieldNames.clear();
CustomerFilterConfig.fieldNames.addAll(Arrays.asList(fields.split(",")));