JSONObject简介

1.JAR包简介

JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。

 

要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:

  1. commons-lang.jar
  2. commons-beanutils.jar
  3. commons-collections.jar
  4. commons-logging.jar 
  5. ezmorph.jar
  6. json-lib-2.2.2-jdk15.jar

2.JSONObject对象使用

JSON-lib包是一个beans,collections,maps,java arrays 和XML和JSON互相转换的包。在本例中,我们将使用JSONObject类创建JSONObject对象,然后我们打印这些对象的值。为了使用 JSONObject对象,我们要引入"net.sf.json"包。为了给对象添加元素,我们要使用put()方法。

2.1.实例1

package foo;
import net.sf.json.JSONArray;     
import net.sf.json.JSONObject;     
    
public class JSONObjectSample {     
        
    //创建JSONObject对象     
    private static JSONObject createJSONObject(){     
        JSONObject jsonObject = new JSONObject();     
        jsonObject.put("k1", "a");     
        jsonObject.put("k2", 2);     
        jsonObject.put("k3",3);     
        jsonObject.put("k4", "44");    
        //还可以     
        jsonObject.element("5", "5");     
        return jsonObject;     
    }
    
    //创建JSONArray对象     
    private static JSONArray createJSONArray(){     
        JSONArray jsonArray = new JSONArray();     
        jsonArray.add(0, "array0");     
        jsonArray.add(1,"array1");        
        return jsonArray;     
    }
    
    
    private static void is(JSONObject jsonObject){
        //判读输出对象的类型     
        boolean isArray = jsonObject.isArray();     
        boolean isEmpty = jsonObject.isEmpty();     
        boolean isNullObject = jsonObject.isNullObject();     
        System.out.println("isArray:"+isArray+" isEmpty:"+isEmpty+" isNullObject:"+isNullObject);  
    }
    
    
    
    public static void main(String[] args) {     
        JSONObject jsonObject = JSONObjectSample.createJSONObject();     
        //输出jsonobject对象     
        System.out.println("jsonObject==>"+jsonObject);     
        
        //取值
        System.out.println("get==>"+jsonObject.get("k1"));
        System.out.println("getString==>"+jsonObject.getString("k2"));        
      
        is(jsonObject);
                     
        //返回一个JSONArray对象     
        JSONArray jSONArray=JSONObjectSample.createJSONArray();
        System.out.println("jSONArray==>"+jSONArray);
            
        jsonObject.element("jsonArray", jSONArray);      
        System.out.println("element了jSONArray之后==>"+jsonObject);    
        
        //第一种
        JSONArray array = jsonObject.getJSONArray("jsonArray");     
        System.out.println("getJSONArray返回一个JSONArray对象:"+array);
        //第二种
        Object array2 = jsonObject.get("jsonArray");     
        System.out.println("get返回一个JSONArray对象:"+(JSONArray)array2);
          
                 
    }     
}    

 

posted @ 2014-12-19 15:40  crazyYong  阅读(721)  评论(0编辑  收藏  举报