美文网首页
Springboot自定义Json注解过滤属性

Springboot自定义Json注解过滤属性

作者: xiaoyiyiyo | 来源:发表于2018-04-27 18:33 被阅读2105次

问题: 在controller层有两个接口返回同一个pojo, 如何做到按需返回不同的json,即控制返回哪些字段?(常见于返回列表和详情)

  1. json与pojo一对一, 即建立不同的pojo。
  2. 依旧是建立两个pojo,有继承关系而已。
  3. 利用json工具包在返回数据之前自定义拼装数据,需要手动编写。

并不喜欢上面的方案,所以搜索了不少资料,千辛万苦定位到两个博客(不够熟悉框架原理的苦 =。=),拼凑出解决方案: 自定义json注解, 效果如下:

    @GET
    @Path("/students")
    @Json(type = Student.class, filter="phone,address")
    public Response listAllStudents() {

        long startMs = System.currentTimeMillis();

        return RespUtils.success(StudentService.listAll(), startMs);
    }

    @GET
    @Path("/student/{studentId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getStudentById(@PathParam("studentId") long studentId) {

        long startMs = System.currentTimeMillis();

        return RespUtils.success(StudentService.getStudentById(studentId), startMs);
    }

两个博客地址:
====> Spring MVC 更灵活的控制json返回(自定义过滤字段)
    这个用于spring mvc 不适用于springboot + jersey (烦恼了很久)
====> REST 请求处理
    看到这个突然有了灵感,可以结合上面那个博客拼凑一把。

最终代码实现(结合上面的两个,代码靠copy):
1. 定义注解 @Json @Jsons
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Jsons.class)
public @interface Json {

    Class<?> type();

    String include() default "";

    String filter() default "";
}

@Jsons让方法支持多重@Json注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Jsons {

    Json[] value();
}
2. 自定义一个json过滤器 JacksonJsonFilter

ps : 我们可以通过ObjectMapper.setFilterProvider来进行过滤规则的设置,jackson内置了一个SimpleFilterProvider过滤器,但是比较单一。

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;

@JsonFilter("JacksonFilter")  // !!!注意这里,需要加上这个注解,坑了我好久
public class JacksonJsonFilter extends FilterProvider{

    Map<Class<?>, Set<String>> includeMap = new HashMap<>();
    Map<Class<?>, Set<String>> filterMap = new HashMap<>();

    public void include(Class<?> type, String[] fields) {
        addToMap(includeMap, type, fields);
    }

    public void filter(Class<?> type, String[] fields) {
        addToMap(filterMap, type, fields);
    }

    private void addToMap(Map<Class<?>, Set<String>> map, Class<?> type, String[] fields) {
        Set<String> fieldSet = map.getOrDefault(type, new HashSet<>());
        fieldSet.addAll(Arrays.asList(fields));
        map.put(type, fieldSet);
    }

    @Override
    public BeanPropertyFilter findFilter(Object filterId) {
        throw new UnsupportedOperationException("Access to deprecated filters not supported");
    }

    @Override
    public PropertyFilter findPropertyFilter(Object filterId, Object valueToFilter) {

        return new SimpleBeanPropertyFilter() {

            @Override
            public void serializeAsField(Object pojo, JsonGenerator jgen, 
                    SerializerProvider prov, PropertyWriter writer)
                    throws Exception {
                if (apply(pojo.getClass(), writer.getName())) {
                    writer.serializeAsField(pojo, jgen, prov);
                } else if (!jgen.canOmitFields()) {
                    writer.serializeAsOmittedField(pojo, jgen, prov);
                }
            }
        };
    }

    private boolean apply(Class<?> type, String name) {
        Set<String> includeFields = includeMap.get(type);
        Set<String> filterFields = filterMap.get(type);
        if (includeFields != null && includeFields.contains(name)) {
            return true;
        } else if (filterFields != null && !filterFields.contains(name)) {
            return true;
        } else if (includeFields == null && filterFields == null) {
            return true;
        }
        return false;
    }
}
3. CustomerJsonSerializer 封装上两步,直接用于Json解析

用一个类封装解析注解和设置过滤器的过程。

import org.springframework.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssga.ssgai.pim.common.annotation.Json;
import com.ssga.ssgai.pim.common.provider.test;

public class CustomerJsonSerializer {

    ObjectMapper mapper = new ObjectMapper();
    JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();

    /**
     * @param clazz target type
     * @param include include fields
     * @param filter filter fields
     */
    public void filter(Class<?> clazz, String include, String filter) {
        if (clazz == null) return;
        if (!StringUtils.isEmpty(include)) {
            jacksonFilter.include(clazz, include.split(","));
        }
        if (!StringUtils.isEmpty(filter)) {
            jacksonFilter.filter(clazz, filter.split(","));
        }
        mapper.addMixIn(clazz, jacksonFilter.getClass());
    }

    public String toJson(Object object) throws JsonProcessingException {
        mapper.setFilterProvider(jacksonFilter);
        return mapper.writeValueAsString(object);
    }
    public void filter(Json json) {
        this.filter(json.type(), json.include(), json.filter());
    }

    /**
     * 用于测试自定义是否起作用
     * @param args
     * @throws JsonProcessingException
     */
    public static void main(String args[]) throws JsonProcessingException {
        CustomerJsonSerializer cjs= new CustomerJsonSerializer();
        cjs.filter(Test.class, "name,age", null);  

        String include = cjs.toJson(new Test()); 

        cjs = new CustomerJsonSerializer();
        // 设置转换 Test 类时,过滤掉 name
        cjs.filter(Test.class, null, "name");  

        String filter = cjs.toJson(new Test());

        System.out.println("include: " + include);
        System.out.println("filter: " + filter);   
      }
}
4. 融入Jersey,控制controller返回的数据(关键的一步)

原理见所给的博客

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Arrays;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import com.XXXXXXX.annotation.Json;
import com.XXXXXX.annotation.Jsons;

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonBodyWriter implements MessageBodyWriter<Object>{

    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
            MediaType mediaType) {

        for (Annotation annotation : annotations) {
            if (annotation instanceof Json || annotation instanceof Jsons) {
                return true;
            }
        }
        return false;
    }

    @Override
    public long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations,
            MediaType mediaType) {

        return -1;
    }

    @Override
    public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations,
            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
            OutputStream entityStream) throws IOException, WebApplicationException {
        CustomerJsonSerializer jsonSerializer = new CustomerJsonSerializer();
        Arrays.asList(annotations).forEach(a -> {
            if (a instanceof Json) {
                Json json = (Json) a;
                jsonSerializer.filter(json);
            } else if (a instanceof Jsons) {
                Jsons jsons = (Jsons) a;
                Arrays.asList(jsons.value()).forEach(json -> {
                    jsonSerializer.filter(json);
                });
            }
        });
        entityStream.write(jsonSerializer.toJson(t).getBytes());
    }

}
5. 启用Provider
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

import com.XXXXXX.ExceptionMapperSupport;
import com.XXXXXX.JsonBodyWriter;

@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {

        //response message writer
        register(JsonBodyWriter.class);

        //exceptions
        register(ExceptionMapperSupport.class);

    }

}



大功告成。做下笔记=。=,可用于util,扩充自己的代码库与风格。

如有bug或更好的方案,告诉我一下下呗。

相关文章

网友评论

      本文标题:Springboot自定义Json注解过滤属性

      本文链接:https://www.haomeiwen.com/subject/jdrilftx.html