将json转换为jsonp格式

private static final String JAVASCRIPT_TYPE = "text/javascript";

ObjectMapper mapper = new ObjectMapper();

String jsonString = null;

try {
jsonString = mapper.writeValueAsString(object);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}


String result = new StringBuilder().append(callbackName).append("(").append(jsonString).append(");").toString();


// 渲染Content-Type为javascript的返回内容,输出结果为javascript语句, 如callback197("{html:'Hello World!!!'}");

render(JAVASCRIPT_TYPE, result, headers);


/**
* 直接输出内容的简便函数.

* eg. render("text/plain", "hello", "encoding:GBK"); 
* render("text/plain", "hello", "no-cache:false"); 
* render("text/plain", "hello", "encoding:GBK", "no-cache:false");

* @param contentType
*            String 数据报
* @param content
*            String 数据内容
* @param headers
*            String... 可变的header数组,目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
*/
public static void render(final String contentType, final String content, final String... headers) {
HttpServletResponse response = initResponse(contentType, headers);
PrintWriter out = null;
try {
out = response.getWriter();
out.write(content);
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}

猜你喜欢

转载自blog.csdn.net/ww598260073/article/details/75382467