com.ruijc.fastjson.FastjsonHttpMessageConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spring-boot-starter-fastjson Show documentation
Show all versions of spring-boot-starter-fastjson Show documentation
Springboot自动化配置Fastjson框架并支持JSONP操作。
/*
* 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);
}
}