前言: 数据库的字段比如:price:1 ,返回需要price:1元。 这时两种途径修改: ① 比如sql中修改或者是在实体类转json前遍历修改。 ②返回json,序列化时候修改。用到的是fastjson。要求fastjson版本1.2.15以上(本章介绍) 操作: 首先pom修改依赖这里我要返回的图片路径 在返回时候字段前面拼接一个 /files com.alibaba fastjson 1.2.29
@JSONField(serializeUsing = JSONFieldViewPathSerializerUtil.class) private String idcardImages;
JSONFieldViewPathSerializerUtil 是此字段序列化要用的类
public class JSONFieldViewPathSerializerUtil implements ObjectSerializer { static StorageProperties storageProperties; @Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) { // 这里从spring中获取bean 为了取 "/files" ,可以忽略不看 if (null == storageProperties) { storageProperties = SpringUtil.getBean(StorageProperties.class); } //主要看这里 if (StringUtils.isNotBlank(object.toString())) { String value = object.toString(); //拼接 "/files" value = storageProperties.getRequestLocation() + value; serializer.write(newValue); } else { serializer.write(String.valueOf(object)); } }}
注意事项:
1、String序列化时候 如果是null 会在返回的时候变成 " "空字符串,判断时候需要注意
2、在要序列化的字符串是空 " " 也要 执行方法:serializer.write(String.valueOf(object));
否则返回的json 是“ idcardImages: ,” 注意格式是错误的
扩展:SpringUtil从容器中获取bean
/** * @Auther liran * @Date 2018/8/30 14:49 * @Description */import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; } System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringUtil.applicationContext+"========"); } //获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通过name获取 Bean. public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通过class获取Bean. public staticT getBean(Class clazz){ return getApplicationContext().getBean(clazz); } //通过name,以及Clazz返回指定的Bean public static T getBean(String name,Class clazz){ return getApplicationContext().getBean(name, clazz); }}