读书人

JSON应用的例子

发布时间: 2012-09-13 09:51:53 作者: rapoo

JSON使用的例子

使用的软件包

?

1 客户端?? json2.js

2 服务端?? json_simple-1.1.jar

?

客户端

//1 字符串装换为对象,使用JSON的parse方法alert("begin");var text = '{"a":"1", "b":"2", "c":"3"}';var jsonObject = JSON.parse(text, null);alert("The jsonObject value is " +jsonObject.a + ";" + jsonObject.b + ";" + jsonObject.c);//2 对象转换为字符串,使用JSON的stringify方法alert(JSON.stringify(jsonObject));//3 使用eval代替parse方法var jsonObject2 = eval('(' + text + ')'); //这里直接写 eval(text) 会报错的alert("The jsonObject2 value is " +jsonObject2.a + ";" + jsonObject2.b + ";" + jsonObject2.c);

?

?

?

服务端

?

?

?

import org.json.simple.JSONArray;import org.json.simple.JSONObject;import org.json.simple.parser.JSONParser;import org.json.simple.parser.ParseException;public class JsonTest {/** * @param args */@SuppressWarnings("unchecked")public static void main(String[] args) {//1 json对象转换为字符串JSONObject subObject = new JSONObject();subObject.put("ooo", "***");subObject.put("ppp", "&&&");JSONObject object = new JSONObject();object.put("aaa", "111");object.put("bbb", "222");object.put("ccc", subObject);System.out.println(object.toJSONString());//2 json数组对象装换为字符串JSONArray array = new JSONArray();JSONObject object1 = new JSONObject();object1.put("aaa", "111");object1.put("bbb", "222");JSONObject object2 = new JSONObject();object2.put("aaa", "111");object2.put("bbb", "222");array.add(object1);array.add(object2);System.out.println(array.toJSONString());//3 字符串转换为json对象String jsonStr = "{\"aaa\":\"111\",\"ccc\":{\"ooo\":\"***\",\"ppp\":\"&&&\"},\"bbb\":\"222\"}";JSONParser parser = new JSONParser();try {JSONObject parseObject = (JSONObject)parser.parse(jsonStr);System.out.println("---->" + parseObject.toJSONString());} catch (ParseException e) {e.printStackTrace();}//4 字符串转换为数组jsonStr = "[{\"aaa\":\"111\",\"bbb\":\"222\"},{\"aaa\":\"111\",\"bbb\":\"222\"}]";try {JSONArray parseObject = (JSONArray)parser.parse(jsonStr);System.out.println("---->" + parseObject.toJSONString());} catch (ParseException e) {e.printStackTrace();}}}

?

?

读书人网 >JavaScript

热点推荐