51,409
社区成员
发帖
与我相关
我的任务
分享{
userName: "nihao",
sex: "male",
age: "23"
} <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<!-- 导入两个js文件 -->
<script type="text/javascript" src="./ajax.js"></script>
<script type="text/javascript" src="./prototype1.6.js"></script>
<title>jsontest.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=GB18030">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
var req = createXMLHttpRequest();
function startRequest(){
try{
req.onreadystatechange = handleStateChange;
req.open("GET", "user.txt", true);
req.send(null);
}catch(exception){
alert("");
}
}
function handleStateChange(){
if(req.readyState == 4){
if (req.status == 200 || req.status == 0){
// 取得返回字符串
var resp = req.responseText;
// 构造返回JSON对象的方法
var func = new Function("return " + resp);
// 得到JSON对象
var json = func( );
// 显示返回结果
alert("userName: " + json.userName + " " + "sex: " + json.sex + " " + "age: " + json.age);
}
}
}
</script>
</head>
<body>
<div>
<input type="button" value="json's value"
onclick="startRequest();" />
</div>
</body>
</html>package test;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class StrJson1 {
public static void main(String[] args) {
String json = "{'name': '呵呵','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'上海'}";
try {
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
String address = jsonObject.getString("address");
System.out.println("name is:" + name);
System.out.println("address is:" + address);
JSONArray jsonArray = jsonObject.getJSONArray("array");
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println("item " + i + " :" + jsonArray.getString(i));
try{
JSONObject jsonObject333 = new JSONObject(jsonArray.getString(i));
String aaaa = jsonObject333.getString("a");
System.out.println("----------"+aaaa);
}catch(Exception e){
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}