一,使用 SerializeFilter
过滤掉 @class
字段(服务器端)
import com.alibaba.fastjson.serializer.NameFilter;import java.util.Map;public class RemoveClassFilter implements NameFilter {@Overridepublic String process(Object object, String name, Object value) {if ("@class".equals(name)) {return null; // 返回 null 表示忽略该字段}return name;}
}
二,在 FastJsonConfig
中应用这个过滤器:
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;import java.util.List;@Configuration
public class WebConfig {@Beanpublic HttpMessageConverter<?> fastJsonHttpMessageConverter() {FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();FastJsonConfig config = new FastJsonConfig();// 添加自定义的 SerializeFilterconfig.setSerializeFilters(new RemoveClassFilter());// 禁用自动类型检测config.getParserConfig().setAutoTypeSupport(false);converter.setFastJsonConfig(config);return converter;}// 如果你想覆盖默认的消息转换器,可以这样做:/*@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(fastJsonHttpMessageConverter());}*/
}