JSONArray和JSONObject

JSONObject的数据用{}来表示,如:

{ "id" : "123", "courseID" : "huangt-test", "title" : "提交作业"}  

JSONArray是由JSONObject构成的数组,用[{},{}]来表示,如:

[{"id" : "123", "courseID" : "huangt-test", "title" : "提交作业"},  {"beginTime" : 1398873600000  "endTime"}] ;

接下来看一下具体的例子:

package jsontest;

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

public class JSONObjectSample {

    // 创建JSONObject对象
    private static JSONObject createJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "huangwuyi");
        jsonObject.put("sex", "男");
        jsonObject.put("QQ", "413425430");
        jsonObject.put("Min.score", new Integer(99));
        jsonObject.put("nickname", "梦中心境");
        return jsonObject;
    }

    public static void main(String[] args) {
        JSONObject jsonObject = JSONObjectSample.createJSONObject();
        // jsonObject:{"username":"huangwuyi","sex":"男","QQ":"413425430","Min.score":99,"nickname":"梦中心境"}
        System.out.println("jsonObject:" + jsonObject);

        boolean isArray = jsonObject.isArray();  //false
        boolean isEmpty = jsonObject.isEmpty();  //false
        boolean isNullObject = jsonObject.isNullObject();  //false

        // 添加属性
        jsonObject.element("address", "福建省厦门市");

        // 返回一个JSONArray对象
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0, "this is a jsonArray value");
        jsonArray.add(1, "another jsonArray value");
        jsonObject.element("jsonArray", jsonArray);
        //获取追加的名为"jsonArray"的一个jsonArray
        JSONArray array = jsonObject.getJSONArray("jsonArray");
        //{"username":"huangwuyi","sex":"男","QQ":"413425430","Min.score":99,"nickname":"梦中心境","address":"福建省厦门市","jsonArray":["this is a jsonArray value","another jsonArray value"]}
        System.out.println(jsonObject);

        // 根据key返回一个字符串
        String username = jsonObject.getString("username");

        // 把字符转换为 JSONObject
        String temp = jsonObject.toString();
        JSONObject object = JSONObject.fromObject(temp);

    }

}

注意一下JSONObject的put()和element()方法的区别: 
public Object put (Object key, Object value): 
将value映射到key下。如果此JSONObject对象之前存在一个value在这个key下,当前的value会替换掉之前的value 
public JSONObject element (String key, Object value): 
将键/值对放到这个JSONObject对象里面。如果当前value为空(null),那么如果这个key存在的话,这个key就会移除掉。

 

posted @ 2018-06-19 11:11  LittleMoon  阅读(721)  评论(0编辑  收藏  举报