Spring MVC JSON转换自定义注解

阅读更多

1.JSON转换

package cn.com.shopec.app.convert;

import cn.com.shopec.app.common.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;


/**
 * Created by guanfeng.li on 2016/7/18.
 */
public class JSONHttpMessageConverter extends FastJsonHttpMessageConverter {

    private Log log = LogFactory.getLog(JSONHttpMessageConverter.class);

    //字符集
    private String charset = "UTF-8";
    //漂亮格式化
    private boolean prettyFormat = false;
    private boolean recordeResult = true;

    @Override
    protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        if(obj instanceof Result){
//            writer(obj, outputMessage);
            writerResult(obj, outputMessage);
        }else{
            super.writeInternal(obj, outputMessage);
        }
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * json转换
     */
    private void writerResult(Object obj, HttpOutputMessage outputMessage) throws IOException {
        Result result = (Result) obj;
        result.addSerializerFeature(SerializerFeature.SortField,SerializerFeature.DisableCircularReferenceDetect);
        if(prettyFormat){
            result.addSerializerFeature(SerializerFeature.PrettyFormat);
        }
        String json = result.toString();
        OutputStream out = null;
        try {
            out = outputMessage.getBody();
            out.write(json.getBytes(charset));
            out.flush();
        } finally {
            out.close();
        }
        if(recordeResult){
            log.info("JSON:"+json);
        }
    }

    //json转换
    private void writer(Object obj, HttpOutputMessage outputMessage) throws IOException {
        Result result = (Result) obj;
        result.addSerializerFeature(SerializerFeature.SortField);
        if(prettyFormat){
            result.addSerializerFeature(SerializerFeature.PrettyFormat);
        }
        result.addSerializeFilter(Result.class,"jsonConfig,jsonFeatures,jsonFilter",false);

        SerializerFeature[] features = new SerializerFeature[result.getJsonFeatures()==null?0:result.getJsonFeatures().size()];
        if(result.getJsonFeatures()!=null){
            result.getJsonFeatures().toArray(features);
        }

        SerializeFilter[] filters = new SerializeFilter[result.getJsonFilter()==null?0:result.getJsonFilter().size()];
        if(result.getJsonFilter()!=null){
            result.getJsonFilter().toArray(filters);
        }
        SerializeConfig jsonConfig = result.getJsonConfig();
        String json ;
        if(jsonConfig!=null){
            json = JSON.toJSONString(obj,jsonConfig,filters,features);
        }else{
            json = JSON.toJSONString(obj,filters,features);
        }
        outputMessage.getBody().write(json.getBytes(charset));
        log.info("返回JSON结果:\n"+json);
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public void setPrettyFormat(boolean prettyFormat) {
        this.prettyFormat = prettyFormat;
    }

    public void setRecordeResult(boolean recordeResult) {
        this.recordeResult = recordeResult;
    }
}

 

2.自定义注解

package cn.com.shopec.app.mvc.annotation;

import java.lang.annotation.*;

/**
 * Created by guanfeng.li on 2016/8/26.
 */
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestAttribute {

    String value() default "";

}

 

package cn.com.shopec.app.mvc.support;

import cn.com.shopec.app.mvc.annotation.RequestAttribute;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by guanfeng.li on 2016/8/26.
 */
public class RequestAttributeHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        RequestAttribute requestAttribute = parameter.getParameterAnnotation(RequestAttribute.class);
        if(requestAttribute!=null){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        if(req!=null){
            RequestAttribute requestAttribute = parameter.getParameterAnnotation(RequestAttribute.class);
            String value = requestAttribute.value();
            if(StringUtils.isNotEmpty(value)){
                return req.getAttribute(value);
            }

            if(StringUtils.isEmpty(value)){
                String parameterName = parameter.getParameterName();
                return req.getAttribute(parameterName);
            }
        }
        return null;
    }
}

 3.Spring MVC配置文件




	
		
	

    
    
        
        
        
    


    

    
        
            
                
            
            
                
                    
                        text/plain;charset=UTF-8
                    
                
                
                
                
                
            
        
        
            
        
    

    
	
    
	
	

	
	

	
		
			UTF-8
		
		
			32505856
		
		
			4096
		
	


    
    

    
    
        
        
            
                error
            
        
    

    
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
    


 4.接口消息实体类

package cn.com.shopec.app.common;


import cn.com.shopec.core.common.PageFinder;
import cn.com.shopec.core.common.Query;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.*;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.*;

/**
 * Created by guanfeng.li on 2016/7/8.
 * APP接口返回实体类
 */
public class Result implements Serializable {

    //状态码
    private String status = "200";
    //消息提示
    private String msg = "";
    //响应数据
    private Object data;
    //分页
    private PageFinder page;

    //json格式化
    private SerializeConfig jsonConfig;
    //json 特性配置
    private Set jsonFeatures;
    //json 属性过滤
    private Set jsonFilter;

    public Result() {

    }

    public Result(Object data, Query query, long rowCount) {
        this.data = data;
        this.page = new PageFinder<>(query.getPageNo(), query.getPageSize(), rowCount);
    }

    public Result(String status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public Result(Object data) {
        this.data = data;
    }

    public Result(Object data,PageFinder page) {
        this.data = data;
        this.page = page;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * 特性配置
     */
    public Result addSerializerFeature(SerializerFeature... serializerFeatures) {
        addSerializerFeature(3, serializerFeatures);
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * 特性配置
     */
    public Result addSerializerFeature(int size, SerializerFeature... serializerFeatures) {
        if (jsonFeatures == null) {
            jsonFeatures = new HashSet<>(size);
        }
        for (SerializerFeature item : serializerFeatures) {
            jsonFeatures.add(item);
        }
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * json 属性过滤
     */
    public Result addSerializeFilter(Class clazz, String properties) {
        addSerializeFilter(3, clazz, properties, true);
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * json 属性过滤
     */
    public Result addSerializeFilter(Class clazz, String properties, boolean isinclude) {
        addSerializeFilter(3, clazz, properties, isinclude);
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * json 属性过滤
     */
    public Result addSerializeFilter(int size, Class clazz, String properties, boolean isinclude) {
        if (jsonFilter == null) {
            jsonFilter = new HashSet<>();
        }
        if(clazz!=null && properties==null){
            jsonFilter.add(new SimplePropertyPreFilter(clazz));
            return this;
        }
        if(clazz==null && properties!=null){
            jsonFilter.add(new SimplePropertyPreFilter(properties.split(",")));
            return this;
        }
        if (!isinclude) {
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(clazz);
            filter.getExcludes().addAll(Arrays.asList(properties.split(",")));
            jsonFilter.add(filter);
        } else {
            jsonFilter.add(new SimplePropertyPreFilter(clazz, properties.split(",")));
        }
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * 过滤分页信息
     */
    public Result filterPage(){
        addSerializeFilter(this.getClass(),"page",false);
        return  this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * json格式化
     */
    public Result putSerializeConfig(Class cls, ObjectSerializer value) {
        putSerializeConfig(3, cls, value);
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * json格式化
     */
    public Result putSerializeConfig(int size, Class cls, ObjectSerializer value) {
        if (jsonConfig == null) {
            jsonConfig = new SerializeConfig(size);
        }
        jsonConfig.put(cls, value);
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * 空字符串显示 “”
     * 空集合 []
     * 空Map {}
     * Number 0
     */
    public Result writeNullStringNumberListAsEmpty() {
        addSerializerFeature(5, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty);
        return this;
    }

    public Result writeNullStringAsEmpty() {
        addSerializerFeature(2, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
        return this;
    }

    public Result writeNullListAsEmpty() {
        addSerializerFeature(2, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty);
        return this;
    }

    public Result writeNullNumberAsZero() {
        addSerializerFeature(2, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero);
        return this;
    }

    /**
     * Created by guanfeng.li   2016/7/19
     * 漂亮格式化
     */
    public Result prettyFormat() {
        addSerializerFeature(SerializerFeature.PrettyFormat);
        return this;
    }

    //添加返回结果
    public Result put(String key, Object value) {
        if (data == null) {
            data = new HashMap();
        } else {
            if (!(data instanceof Map)) {
                return this;
            }
        }

        ((Map) data).put(key, value);
        return this;
    }

    public String getStatus() {
        return status;
    }

    public Result setStatus(String status) {
        this.status = status;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public Result setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public PageFinder getPage() {
        return page;
    }

    public Result setPage(PageFinder page) {
        this.page = page;
        return this;
    }

    public SerializeConfig getJsonConfig() {
        return jsonConfig;
    }

    public Set getJsonFeatures() {
        return jsonFeatures;
    }

    public Set getJsonFilter() {
        return jsonFilter;
    }

    @Override
    public String toString() {
        if (jsonFilter != null || jsonFeatures != null || jsonConfig != null) {
            addSerializeFilter(Result.class, "jsonConfig,jsonFeatures,jsonFilter", false);
        }
        SerializerFeature[] features = new SerializerFeature[jsonFeatures == null ? 0 : jsonFeatures.size()];
        if (jsonFeatures != null) {
            jsonFeatures.toArray(features);
        }

        SerializeFilter[] filters = new SerializeFilter[jsonFilter == null ? 0 : jsonFilter.size()];
        if (jsonFilter != null) {
            jsonFilter.toArray(filters);
        }
        String json;
        if (jsonConfig != null) {
            json = JSON.toJSONString(this, jsonConfig, filters, features);
        } else {
            json = JSON.toJSONString(this, filters, features);
        }
        return json;
    }
}

 

你可能感兴趣的:(spring,mvc,自定义注解,JSON转换)