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

标签 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.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);
    }

我的情况是,我想仅为选定的字段返回自定义“客户”。

我正在使用 jax-rs、jackson 将对象解码/编码为 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",
}

=> 选择后的结果:fields =phoneNumber,customerId

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

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

最佳答案

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

@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;
      } 


}

然后将该过滤器添加到您的模型中:

@JsonFilter("customerFilter")
public class Customer {...}

最终使用该过滤器:

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

关于java - 在编码之前动态隐藏一些字段(java 到 json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51653444/

相关文章:

使用 Jackson 将 Java 属性文件转换为 JSON

java - 使用 Jackson 和 Json-View 排除 json 中的字段

java - Spring 3.1 WebApplicationInitializer & Embedded Jetty 8 AnnotationConfiguration

java - Java 字符串中的底层容器是什么?

Java 多线程 - 有没有办法同步/锁定映射中的特定值以进行读取和写入?

Java 8 将列表拆分为 block 进行处理并在返回结果之前将其合并回来

java - Log4j 验证异常是否作为最后一个参数传递

java - Android 应用程序解析 JSON 数据错误?

java - Ant 大战僵尸游戏

java - 在 foreach 循环中使用 BufferedWriter 生成新行时出现问题