背景

因为懒惰将thrift生成的对象直接在controller输出,被前端吐槽一堆字段

代码

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

@Configuration
public class JacksonConfig {
    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder()
                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .serializerByType(TBase.class, new ThriftSerializer())
                .failOnUnknownProperties(false);
    }

    public static class ThriftSerializer extends JsonSerializer<TBase> {
        @Override
        public void serialize(TBase value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            try {
                TProtocolFactory f = new TSimpleJSONProtocol.Factory();
                String s = new TSerializer(f).toString(value, "UTF-8");
                jgen.writeRawValue(s);
            }
            catch (TException e) {
                throw new IOException(e);
            }
        }
    }
}
  • 感谢github的参考代码,网址*

fastjson序列化简洁thrift json

public static void main(String[] args) {
        Request request = new Request()
                .setPageNo(5)
                .setPageSize(10);
        PropertyPreFilter propertyPreFilter = (jsonSerializer, resObj, name) -> {
            if (resObj instanceof Map || resObj instanceof List) {
                return true;
            }
            if ("metaDataMap".equals(name)) {
                return false;
            }
            List<String> fieldNames = new ArrayList<>();
            Field[] fields = resObj.getClass().getFields();
            for (Field field : fields) {
                fieldNames.add(field.getName());
            }
            return fieldNames.contains(name);
        };
        System.out.println(JSONObject.toJSONString(request)); //输出{"pageNo":5,"pageSize":10,"setPageNo":true,"setPageSize":true}
        System.out.println(JSONObject.toJSONString(request, propertyPreFilter)); //输出{"pageNo":5,"pageSize":10}
    }

PropertyPreFilter类实际使用时抽一个公共单例类出来

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyPreFilter;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Objects;


public class ThriftJsonPropertyPreFilter implements PropertyPreFilter {

    private final static ThriftJsonPropertyPreFilter INSTANCE = new ThriftJsonPropertyPreFilter();

    public static ThriftJsonPropertyPreFilter getInstance() {
        return INSTANCE;
    }

    @Override
    public boolean apply(JSONSerializer jsonSerializer, Object o, String name) {
        if (o instanceof Map || o instanceof List) {
            return true;
        }
        if ("metaDataMap".equals(name)) {
            return false;
        }
        Field[] fields = o.getClass().getFields();
        for (Field field : fields) {
            if(Objects.equals(field.getName(), name)) {
                return true;
            }
        }
        return false;
    }
}
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐