java中map转为json数据_Java技术-将java中Map类型数据转化为json数据并以Ajax形式返回...
Java技術(shù)-將java中Map類型數(shù)據(jù)轉(zhuǎn)化為json數(shù)據(jù)并以Ajax形式返回html
1、自定義工具類(簡單易用)-下面是我寫的一個簡單的工具類前端
package com.test.util;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
public class ToAjaxJsonString{
// 將Map格式數(shù)據(jù)轉(zhuǎn)換為JSON類型數(shù)據(jù)并返回,不然返回null
public static String ajaxJson(Map jsonMap) {
JSONObject jsonObject = JSONObject.fromObject(jsonMap);//將Java對象(如:Map數(shù)據(jù),ArrayList等)轉(zhuǎn)換為JSONObject類型
//首先jsonObject.toString()將JSONObject類型數(shù)據(jù)轉(zhuǎn)換為json字符串!
return ajax(jsonObject.toString(), "application/json");//而后調(diào)用ajax()方法將json格式字符串以Ajax形式返回前端
}
//將json格式字符串以AJAX形式返回,不然返回null
public static String ajax(String content, String type) {
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType(type + ";charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(content);
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
調(diào)用示例return null;
}
}
2、調(diào)用自定義工具類處理Map數(shù)據(jù)并以Ajax技術(shù)將json數(shù)據(jù)返回?-示例java
下面是我寫的一個簡單的工具類調(diào)用例子:ajax
package com.test.bean;
import java.util.HashMap;
import java.util.Map;
importcom.test.util.ToAjaxJsonString; //引入自定義的工具類
public class Test {
public static void main(String[] args) {
Map map = new HashMap();
map.put( "name", "zhangsan" );
map.put( "age", new Integer(20) );
map.put( "sex", "male" );
map.put( "bool", Boolean.TRUE );
System.out.println(ToAjaxJsonString.ajaxJson(map));// 輸出{"name":"zhangsan","age":20,"sex":"male","bool":"TRUE",}
return ToAjaxJsonString.ajaxJson(map); //返回json格式數(shù)據(jù){"name":"zhangsan","age":20,"sex":"male","bool":"TRUE",}
}
}
更多內(nèi)容,可參考:http://www.cnblogs.com/hitwtx/articles/2468633.html
總結(jié)
以上是生活随笔為你收集整理的java中map转为json数据_Java技术-将java中Map类型数据转化为json数据并以Ajax形式返回...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java开发怎么打补丁_[Java教程]
- 下一篇: java画个半径为1地圆_java -