JSON serialization (fastjson) using custom annotations in the springboot project

In the development work, there are some user-sensitive fields that need to be processed in the backend, so we want to do it when json is formatted; our project configures fastjson as json serialization; so we want to achieve this by implementing the fastjson interface json configurable formatting;

    The first pit that comes to mind is the custom annotation; the annotation is used to format the json; additional processing is performed; today, the custom annotation is used to achieve a desensitization of the mobile phone number;

First define an annotation:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MobileDesensitization {

}

Then use the interception interface ContextValueFilter provided by fastjson to intercept the field; then change the data;

Note: The type of filter provided by fastjson:

  1. PropertyPreFilter determines whether to serialize according to PropertyName
  2. PropertyFilter determines whether to serialize based on PropertyName and PropertyValue
  3. NameFilter modifies the Key, if you need to modify the Key, the process return value can be
  4. ValueFilter modifies Value
  5. Add content to the front of BeforeFilter serialization
  6. Add content at the end when AfterFilter serializes

The above interfaces are all extended interfaces provided by fastjson;    

We implement it here through the most ContextValueFilter, because the annotations on this property can be easily found in the contextValueFilter; the valueFilter above can actually be implemented as well; but you need to get the annotations for these properties yourself;

@Component
public class MobileContextValueFilter implements ContextValueFilter {
private final static Logger logger = LoggerFactory.getLogger( MobileContextValue Filter .class);
@Overridepublic Object process(BeanContext context, Object object, String name, Object value) {if(value == null || !(value instanceof String)) {return value;}MobileDesensitization annation = context.getAnnation(MobileDesensitization.class);
if(annation == null) {return value;}String propertyValue = (String) value;if (StringUtils.isBlank(propertyValue)) {return "";}propertyValue = "%s****%s".format(propertyValue.subString(0,4),propertyValue.sub(7));return propertyValue;}}配置fastjson为springmvc工程的json序列化的格式化器:

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**");
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		FastJsonHttpMessageConverter fastJson = new FastJsonHttpMessageConverter();
                //WriteNullStringAsEmpty configures null values ​​to be converted into empty strings; WriteNonStringValueAsString configures all values ​​with double quotes
		fastJson.getFastJsonConfig().setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteNonStringValueAsString); //The following contextType needs to be added; otherwise, it will be reported that * cannot match all contextType types;
		List<MediaType> supportedMediaTypes = new ArrayList<>();
		supportedMediaTypes.add(MediaType.APPLICATION_JSON);
		supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
		supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
		supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
		supportedMediaTypes.add(MediaType.APPLICATION_PDF);
		supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
		supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
		supportedMediaTypes.add(MediaType.APPLICATION_XML);
		supportedMediaTypes.add(MediaType.IMAGE_GIF);
		supportedMediaTypes.add(MediaType.IMAGE_JPEG);
		supportedMediaTypes.add(MediaType.IMAGE_PNG);
		supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
		supportedMediaTypes.add(MediaType.TEXT_HTML);
		supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
		supportedMediaTypes.add(MediaType.TEXT_PLAIN);
		supportedMediaTypes.add(MediaType.TEXT_XML);
		fastJson.setSupportedMediaTypes(supportedMediaTypes);
		
		super.configureMessageConverters(converters);
	}

In this way, desensitization can be achieved as long as it is on the serialized field or the get method;





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324674422&siteId=291194637