您的位置:首页 > Web前端 > JavaScript

Json_Ajax 页面交互双向传值

2015-02-05 21:04 323 查看
1. json 跟字符串,数组,map,bean之间的数据转换

    1) JsonObject 

package com.Ip.Ie;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonObject {
public static void main(String[] args) {
String json1 = "{'result':'1', 'returnval':'获取成功', 'recordcount':1, 'table':{'no':1}}";
JSONObject j = JSONObject.fromObject(json1);
System.out.println(j.get("returnval"));

String json2 = "{'result':'1', 'returnval':[{'id':'9'},{'name':'Jack'}]}";
JSONObject r = JSONObject.fromObject(json2);
System.out.println(JSONObject.fromObject(JSONArray.fromObject(r.get("returnval")).get(1)).get("name"));

Map<String,String> mp = new HashMap<String, String>();
mp.put("firstName", "firstName");
mp.put("lastName", "lastName");
JSONObject json3 = JSONObject.fromObject(mp);
System.out.println(json3.get("firstName"));

boolean[] booarry=new boolean[]{true,false,true};
JSONArray json4=JSONArray.fromObject(booarry);
System.out.println(json4.get(2));

Shop shop = new Shop("Marry", "金钟路");
JSONObject json5 = JSONObject.fromObject(shop);
System.out.println(json5.get("name"));

String shopResult = "{'name':'Marry2','property':'金钟路2'}";
JSONObject json6 = JSONObject.fromObject(shopResult);
Shop shop2 = (Shop) JSONObject.toBean(json6,Shop.class);
System.out.println(shop2.getProperty());

}
}

    2) Shop

package com.Ip.Ie;

public class Shop {
private String name;
private String property;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public Shop() {
}
public Shop(String name, String property) {
this.name = name;
this.property = property;
}

}

2. json 和后台数据的双向交互

    1) Serlvet 中间层

package com.servlet;

import java.io.*;
import java.net.*;
import java.text.ParseException;
import javax.servlet.*;
import javax.servlet.http.*;
//import net.sf.json.*;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.*;
import java.text.ParseException;
import javax.servlet.*;
import javax.servlet.http.*;
//import net.sf.json.*;

public class JSONExample extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String line = null;
StringBuffer json = new StringBuffer();
try {
BufferedReader reader = req.getReader();
while((line = reader.readLine()) != null) {
json.append(line);
}
}
catch(Exception e) {
System.out.println("Error reading JSON string: " + e.toString());
}
JSONObject Json = JSONObject.fromObject(json.toString());
System.out.println(Json.get("sex"));
PrintWriter out = resp.getWriter();
out.append("{'Name':'Machel'}");
out.flush();
out.close();
//super.service(req, resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String json = readJSONStringFromRequestBody(request);

//Use the JSON-Java binding library to create a JSON object in Java
JSONObject jsonObject = null;
try {
//如果是用json-lib的话,前面引进的包改为
//import net.sf.json.*; //这里改为
//jsonObject = JSONObject.fromObject(json);
//fromObject(object)是static的。也可以用fromString(string)的,但官方是不建议用fromString的。
jsonObject = JSONObject.fromObject(json);
}
catch(Exception pe) {
System.out.println("ParseException: " + pe.toString());
}

String responseText = "You have a " + jsonObject.getInt("year") + " "
+ jsonObject.getString("make") + " " + jsonObject.getString("model")
+ " " + " that is " + jsonObject.getString("color") + " in color.";

response.setContentType("text/xml");
response.getWriter().print(responseText);
}

private String readJSONStringFromRequestBody(HttpServletRequest request){
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
json.append(line);
}
}
catch(Exception e) {
System.out.println("Error reading JSON string: " + e.toString());
}
return json.toString();
}
}
    2) ajax 页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'ajax.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<div onclick="loadXMLDoc()">click</div>
<span id="span"></span>
<div id="myDiv"></div>
</body>
<script type="text/javascript">
function loadXMLDoc()
{
var htmlText = "{'sex':'man'}";
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var TextHttp = xmlhttp.responseText;
var obj = eval ("(" + TextHttp + ")");
document.getElementById("myDiv").innerHTML=obj.Name;
}
}
xmlhttp.open("POST","/IP/JSONExample/JSONExample?wtd=delete",true);
xmlhttp.send(htmlText);
}
</script>
</html>


3. json 需要支持的包
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json ajax