利用Fastjson的JSONField属性自定义输出函数

编程语言 12/11 阅读 850 views次 人气 0
摘要:

1、自定义自己的输出类,实现ObjectSerializer接口,重写write方法

public class ResUrlComplete  implements ObjectSerializer{ 
    
    private static ResourceUtils resourceUtils;
    
    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if(resourceUtils==null){
            AppContext appcontext = new AppContext();
            resourceUtils = (ResourceUtils)(appcontext.getBean("resourceUtils"));
        }
        String text = (String) object;
        String url = resourceUtils.getCompleteUrl(text);
        serializer.write(url);        
    }    
}

 

2、AppContext类,在springxml中配置,自定义的类

<bean id="appContext" class="com.springmvc.utils.AppContext" />
public class AppContext  implements  ApplicationContextAware{  
  
    private static ApplicationContext applicationContext;  
    /**  
     * 当继承了ApplicationContextAware类之后,那么程序在调用  
     * getBean(String)的时候会自动调用该方法,不用自己操作  
     */  
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext)  
            throws BeansException {  
        this.applicationContext= applicationContext;  
    }
    public Object getBean(String beanName){  
        return this.applicationContext.getBean(beanName);  
    }
}

 

3、ResourceUtils 类,是自定义的类,实现业务数据变换

@Component("resourceUtils")
public class ResourceUtils {
    private Log log = LogFactory.getLog(ResourceUtils.class);

       //自己的方法代码
}

 

4、在输入的pojo对象属性上使用,将按ResUrlComplete类实现的逻辑来序列化输出。

public class HomePageData {

    private String homepageId;
    private String homepageName;
@JSONField(serializeUsing
=ResUrlComplete.class) private String homepageLogoUrl; // 其它代码 }

 

评论

该文章不支持评论!

分享到: