All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ruijc.fastjson.FastjsonHttpMessageConverter Maven / Gradle / Ivy

There is a newer version: 2.2.0
Show newest version
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ruijc.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import java.io.IOException;
import java.io.OutputStream;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

/**
 * 支持JSONP的Fastjson的消息转换器
 *
 * @author Storezhang
 */
public class FastjsonHttpMessageConverter extends com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter {

    @Override
    protected void writeInternal(Object obj, HttpOutputMessage output) throws IOException, HttpMessageNotWritableException {
        String text;
        if (obj instanceof JSONP) {
            JSONP jsonp = (JSONP) obj;
            text = jsonp.getFunction() + "(" + JSON.toJSONString(jsonp.getJson(), getFastJsonConfig().getSerializerFeatures()) + ")";
        } else if (obj instanceof FastjsonFilterWrapper) {
            FastjsonFilterWrapper wrapper = (FastjsonFilterWrapper) obj;
            SerializeFilter[] filters = wrapper.getFilters();
            if (null != filters) {
                text = JSON.toJSONString(wrapper.getObj(), filters, getFastJsonConfig().getSerializerFeatures());
            } else {
                text = JSON.toJSONString(wrapper.getObj(), getFastJsonConfig().getSerializerFeatures());
            }
        } else {
            text = JSON.toJSONString(obj, getFastJsonConfig().getSerializerFeatures());
        }

        write(output, text);
    }

    public String getResult(String text) {
        return text;
    }

    public String getResult(Object obj) {
        return getResult(JSON.toJSONString(obj));
    }

    private void write(HttpOutputMessage output, String text) throws IOException {
        OutputStream out = output.getBody();

        byte[] bytes = getResult(text).getBytes(getFastJsonConfig().getCharset());
        out.write(bytes);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy