【www.guakaob.com--标准员】
服务器端:
public static void main(String[] args) {
Map<Object, Object> dataBaseData = new HashMap<Object, Object>(0); dataBaseData.put("beijing" , "北京"); dataBaseData.put("shanghai", "上海"); dataBaseData.put("wuhan" , "武汉"); StringBuffer jsonData = new StringBuffer(); // 字符流对象 jsonData.append("{"); if (dataBaseData.size() > 0) { } jsonData.deleteCharAt(jsonData.lastIndexOf(",")); if (dataBaseData.size() > 0) { } jsonData.append("}"); jsonData.append("]"); jsonData.append("root:["); Iterator<Entry<Object, Object>> iter = } .iterator(); // 数据库的数据 // 拼接JSON字符流开始 dataBaseData.entrySet() while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); jsonData.append("{"); jsonData.append("wcKey:'" + key + "', wcValue:'" + val + jsonData.append("},"); "'");
// 拼接JSON字符流结束
System.out.println(jsonData.toString()); //
浏览器端:
/* JSP 页面解析将 jsonData 字符串报文解析出来的代码 for(var i=0;i<jsonData.root.length;i++){
} jsonData.root[i].wcKey,httpObj.root[i].wcValue } */
能通讯的原因是:浏览器的通讯标准给了我们编程者一个对象“XMLHttpRequest”,我们需要手动创建他,代码如下:
WEB服务器能够发送json字符的函数,都是J2EE官方包中给我们的函数,如下是我自己的工具类:
/**
* ajax 共通调用
* @author wuchong
* @version $Revision: 1.0 $, $Date: 2012-8-15 下午03:57:05 $
*/
public class AjaxUtil {
/**
* 设置字符编码
*/
public static final void setContentType(HttpServletResponse response) {
// ContentType
response.setContentType("text/html; charset=UTF-8");
// no-cache
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
}
/**
* 页面传值的字符集编码格式转换
* @param String urlVal 页面传值
* @return String 转换后的字符集
*/
public static final String urlDecode(String urlVal) throws Exception {
if (!StringUtils.isEmpty(urlVal)) {
return URLDecoder.decode(urlVal, "UTF-8");
}
return urlVal;
}
/**
* AJAX异步通信参数取得
* @param String[] array 页面传入的参数
*/
public static final String[] getParameters(HttpServletRequest request)
throws Exception {
String[] array = request.getParameterValues("parameters");// /** if (array == null || array.length < 1) {
return null;
}
int len = array.length;
String[] newArray = new String[len];
System.arraycopy(array, 0, newArray, 0, len);
for (int i = 0; i < len; i++) {
// 字符集编码格式转换
newArray[i] = urlDecode(newArray[i].trim());
}
return newArray;
}
/**
* 字符流写入
* @param String 字符流
*/
public static final void write(HttpServletResponse response, String jsonData) {
try {
response.getWriter().write(jsonData);
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* String str 是否为空
* @param str
* @return
*/
public final static boolean isNotEmpty(String str){
return !(str==null||str.trim().length()<1);
}
public final static String null2Space(String str){
return str==null?"":str; }
}
//第一种
public void jsonTx() {
String json = "{'status':200,'message':'查询成功','data':[{'id':1,'name':'name1','describe':'
第一条数据'}]}";
JSONObject data = new JSONObject(json);
int status = data.optInt("status");
JSONArray data1 = data.getJSONArray("data");
if (status==200) {
for(int i=0;i<data1.length();i++){
String s = data1.getString(i);
System.out.println(s);
JSONObject data2 = JSONObject.fromObject(s);
System.out.println(data2.getString("id"));
System.out.println(data2.getString("name"));
System.out.println(data2.getString("describe"));
}
}else if(status==500) {
String msg = data.getString("message");【浏览器是如何解析json的】
System.out.println(msg);
}
}
//第二种
public void getJson() {
String json =
"{'response':{'data':[{'address':'北京','province':'海淀','district':'西三旗','city':'地铁'}]},'status':'ok'}";
JSONObject jsonObject = JSONObject.fromObject(json);
String status = jsonObject.getString("status");
// System.out.println(str);
String response = jsonObject.getString("response");
JSONObject jsonObject2 = JSONObject.fromObject(response);
JSONArray data = jsonObject2.getJSONArray("data");
for(int i=0;i<data.length();i++){
String s = data.getString(i);
JSONObject data2 = JSONObject.fromObject(s);
System.out.println(data2.getString("address"));
System.out.println(data2.getString("province"));
System.out.println(data2.getString("district"));
System.out.println(data2.getString("city"));
}
}
//第三种(只获取json里面数据)【浏览器是如何解析json的】
public static void main(String[] args) {
String json =
"{\"response\":{\"data\":[{\"address\":\"北京\",\"province\":\"海淀\",\"district\":\"三环\",\"city\":\"桥\"}]},\"status\":\"ok\"}";
String str[] =
json.replaceAll(".*\"address\":\"(.*?)\".*\"province\":\"(.*?)\",.*\"district\":\"(.*?)\",.*\"city\":\"(.*?)\".*",
"$2,$4,$3,$1").split(",");
for (String s : str) {
System.out.println(s);
}
}
JS解析JSON数据及取值的一些用法
<%@ page contentType="text/html;charset=GBK" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" /> <title>JS解析JSON数据</title>
</head>
<body style="margin:50px">
<center><h1><b>JS解析JSON数据测试界面</b></h1></center>
<script language="javascript">
//将JSON字符串转换为JSON对象的一些方法
//将JSON字符串转换为JSON对象的一些用法
(function (){
var str = {"name":"张三","age":20};//JSON对象
alert(str.name);alert(str.age);//直接取JSON对象的值
//将JSON字符串转换为JSON对象
var str = "{\"name\":\"张三\",\"age\":\"21\"}";//JSON字符串 转义不用系统/和dos一致用\
var obj = eval('(' + str + ')');//使用eval函数将JSON字符串转换为JSON对象 alert(obj.name);alert(obj.age);【浏览器是如何解析json的】
var str = '{"name":"张三","age":22}';//JSON字符串
var obj = (new Function("return " + str))(); //使用new Function()形式将JSON字符串转换为JSON对象
alert(obj.name);alert(obj.age);
//将JSON对象转换为JSON字符串
//var straa = {"name":"李四","age":"20"};//JSON对象
//var newJSONtext = straa.toJSONString();//貌似没有原生方法
//alert("JSON对象转换为JSON字符串: "+newJSONtext);
})();//(function (){})();自动执行匿名函数
</script>
<script>
//取值的一些用法
//取值的一些用法
function showJSON() {
//效果一
var user =
{
"username":"andy",
"age":20,
"info": { "tel": "123456", "cellphone": "98765"},
"address":
[
{"city":"beijing","postcode":"222333"},
{"city":"newyork","postcode":"555666"}
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
user.username = "Tom";
alert(user.username);
//效果二
var people =
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ]
}
alert(people.programmers[0].firstName+" "+people.programmers[0].email); alert(people.programmers[2].firstName+" "+people.programmers[2].email);
alert(people.authors[0].firstName+" "+people.authors[0].genre);
alert(people.musicians[1].firstName+" "+people.musicians[1].instrument);
}
showJSON();
</script>
</body>
</html>
<script type="text/javascript">
function mm()
{
var str = "";
for (mm in window.event.srcElement)
str += mm+"="+ window.event.srcElement[mm] +"\n"; //得到 srcElement 的所有属性
alert(str);
}
</script>
本文来源:http://www.guakaob.com/jianzhugongchengkaoshi/732480.html
上一篇:民事起诉状格式范文
下一篇:openlaw裁判文书