json-lib的使用《二》

上篇文章主要集中在了使用json-lib来实现JSON字符串和java中的对象的互转上,忽视了json-lib本身的功能,json-lib中有两个类比较重要:JSONObject和JSONArray,这两个类因其名称不同,所实现的功能也不尽相同,JSONObject处理的是对象格式的({}),JSONArray处理的是数组格式的([]),下面看具体的使用方法。

JSONObject

一、源码

JSONObject类中有多个重载的element(),此方法是向JSONObject类中存储数据的方法,通过查看源代码,发现JSONObject是通过Map实现数据存储的,看下面的源码,

 private Map properties;

   /**
    * Construct an empty JSONObject.
    */
   public JSONObject() {
      this.properties = new ListOrderedMap();
   }

在JSONObject中有Map属性,此属性是一个ListOrderMap的对象,element()方法则是向properties中添加数据,因为properties是map,则可以使用操作Map的方法操作properties属性,JSONObject对properties的操作方式进行了包装;从源码中可以发现还有好多重载的get()方法,如,

 public Object get( String key ) {
      verifyIsNull();
      return this.properties.get( key );
   }

从get方法中可以看出使用的便是Map的get方法。

经过以上的源码分析,可以知道对JSONObject的操作即是对Map的操作。

二、使用

public static void TestJSONObject(){
        //创建一个JSONObject对象
        JSONObject jsonObject=new JSONObject();
        
        jsonObject.element("my", "this is my first");
        String str=jsonObject.toString();
        String keyValue=jsonObject.getString("my");
        System.out.println("str:"+str);
        System.out.println("keyValue:"+keyValue);
        
    }

打印结果,

str:{"my":"this is my first"}
keyValue:this is my first

有了JSONObject实例之后,使用element()方法把键和键对应的值添加进去,打印出字符串可以看出是JSON对象的格式,可以看出这种形式和把一个类转化为JSON格式的字符串是一致的,可以把“my”当做是类的属性,“this is my first”是属性的值。
有了这样的理解之后,可以把一个JSON字符串转化为一个JSONObjec对象,然后取得对象中的值,如下,

public static void getValue(){
        String str="{\"my\":\"this is my first\",\"second\":\"this is second!\"}";
        JSONObject jsonObject=JSONObject.fromObject(str);
        String my=jsonObject.getString("my");
        String second=jsonObject.getString("second");
        System.out.println("my:"+my);
        System.out.println("secode:"+second);
        
    }

打印结果如下,

my:this is my first
secode:this is second!

可以看出我们完全可以不把JSON字符串转化为相应的类,同样可以获得想要的值,如果要转化为相应的类,必须要有如下的类,

package com.cn.study.day3;

public class TestAndMy {
    private String my;
    private String second;
    public String getMy() {
        return my;
    }
    public void setMy(String my) {
        this.my = my;
    }
    public String getSecond() {
        return second;
    }
    public void setSecond(String second) {
        this.second = second;
    }
    

}

生成类的代码如下,

public static void getValue(){
        String str="{\"my\":\"this is my first\",\"second\":\"this is second!\"}";
        JSONObject jsonObject=JSONObject.fromObject(str);
        String my=jsonObject.getString("my");
        String second=jsonObject.getString("second");
        System.out.println("my:"+my);
        System.out.println("secode:"+second);
        System.out.println("-------------------------------");
        //生成类
        TestAndMy test=(TestAndMy)jsonObject.toBean(jsonObject, TestAndMy.class);
        System.out.println("my:"+test.getMy()+",second:"+test.getSecond());
        
    }


 

在有些情况下,可能不是这种简单的字符串,而是比较复杂的,我们应该如何取得想要的值呢,看下面的例子,

public static void complex(){
        String str="{\"data\":{\"my\":\"this is my first\",\"second\":\"this is second!\"}}";
        
        JSONObject jsonObject=JSONObject.fromObject(str);
        JSONObject dataObject=jsonObject.getJSONObject("data");
        System.out.println("dd:"+dataObject.toString());
    }

打印结果,

dd:{"my":"this is my first","second":"this is second!"}

在上边的例子中不再是一个JSON对象,而是data对应一个JSON对象,在获得了JSONObject实例之后,我们知道一个JSONObject实例,其底层存储是Map的,那么使用get方法可以获得其键对应的值,可以使用get(String key)方法,此方法返回一个Object对象,返回Object对象之后就不好处理了,此种方法行不通,可以使用getString(String key),此方法是返回key对应的值的字符串形式,那么针对上边的例子,我们返回的应该是{"my":"this is my first","second":"this is second!"},还是达不到最终解析的目的。最终发现使用getJSONObject(String key)方法可以,返回的是JSONObject的对象,那么我们可以接着使用此对象进行完全解析。

JSONArray

一、源码

查看JSONArray的源码,可以发现JSONArray的底层是List实现的,即使用JSONArray对象存储数据是放在List中的,

/**
    * The List where the JSONArray's properties are kept.
    */
   private List elements;
/**    * Construct an empty JSONArray.    */  
public JSONArray() { this.elements = new ArrayList(); }

 

JSONArray中所有的值都是放在elements中的,elements又是ArrayList的一个实例。ArrayList底层是通过数组实现的。那么对于JSONArray的操作就是基于数组的。
JSONArray提供了重载的element()方法,用来新增数据,提供了重载的get()方法来取出数据

二、使用

下面是一个使用JSONArray的例子,

 

public static void testJSONArray(){
        String array="[\"123\",\"this is my test\",{\"address\":\"北京市朝阳区\",\"age\":\"23\",\"name\":\"JSON\"}]";
        JSONArray jsonArray=JSONArray.fromObject(array);
        //由于JSONArray底层是数组,所以这里使用下标的方式来访问其中的元素
        String str1=jsonArray.getString(0);
        String str2=jsonArray.getString(1);
        String str3=jsonArray.getString(2);
        System.out.println("str1:"+str1+",str2:"+str2+",str3:"+str3);
        //由于第三个元素本身是一个对象形式的JSON串,可以这样获得第三个元素
        JSONObject o3=jsonArray.getJSONObject(2);//获得JSONObject对象
        System.out.println("address:"+o3.getString("address")+",age:"+o3.getString("age"));
        
    }

打印结果为,

str1:123,str2:this is my test,str3:{"address":"北京市朝阳区","age":"23","name":"JSON"}
address:北京市朝阳区,age:23

由于JOSNArray是由ArrayList实现的,所有这里是使用getString()方法,可以获得每个索引处的字符串,但是无法做到完全解析此字符串的目的,所以可以使用getJSONObject()方法获得第三个位置的对象,然后解析此对象。

从上边的叙述中可以JSONArray、JOSNObject两个类都可以存储数据,只是使用的方式不同,正是这种不同造成了解析方式不同。

有不正之处,欢迎指出,谢谢!

posted @ 2016-08-23 12:46  良工说技术  阅读(2906)  评论(0编辑  收藏  举报