FastJson小例子(一)

使用的软件包

 

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();
        }
        
    }

}

 

posted on 2017-04-11 15:12  小鸟的士林  阅读(129)  评论(0)    收藏  举报

导航