JSONObject基本內容(三)

參考資料:http://swiftlet.net/archives/category/json    十分感謝!!!~~java

 

第三篇的內容,主要講述的有兩點: 1 .如何獲取JSONObject中對應key的value。   2.如何把JSONObject轉換爲javaBean對象。json

 

一)獲取JSONObject中屬性值swift

首先咱們寫一個javaBean類ide

public class Emp {
    private String name;
    private Integer age;
    private boolean married;
    
    public boolean isMarried() {
        return married;
    }
    public void setMarried(boolean married) {
        this.married = married;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

而後按正常方法,生成對象,把它轉換爲JSONObject,接着看註釋吧~測試

    public static void main(String[] args) {
        Emp emp = new Emp();
        emp.setName("Rime");
        emp.setAge(23);
        emp.setMarried(false);
        
        //轉換爲JSONObject
        JSONObject json = JSONObject.fromObject(emp);
        System.out.println(json.toString());
        
        //利用key獲取屬性值,和map類似
        String name = json.getString("name");
        Integer age = json.getInt("age");
        boolean married = json.getBoolean("married");

        System.out.println(name + "," + age + "," + married);        
    }

輸出結果:this

{"age":23,"married":false,"name":"Rime"}
Rime,23,falsespa

 

看到這裏你或許會有疑問,(1)假如JSONObject中並無這個key存在,會怎麼樣?(2)這個key對應的value的類型錯了,怎麼辦?(3)若是value是複雜數據類型,怎麼辦?.net

既然有疑問,那麼咱們一個一個解決。code

 

(1)咱們故意把"name"寫錯,寫成"nane",結果系統報錯:orm

Exception in thread "main" net.sf.json.JSONException: JSONObject["nane"] not found

爲了防止這種異常,咱們能夠用optXXX方法,來代替getXXX方法。

即:

 String name = json.optString("nane");//當jsonObject中不存在該key時,能夠用optXXX來獲取空值或者默認值,而不是報異常

設置默認值:

String name = json.optString("nane","notExits");

設置默認以後,當nane屬性不存在時,返回notExits字符串。

 

(2)咱們把程序修改一下

        String name = json.getString("age");
        boolean married = json.getBoolean("name");
        Integer age = json.getInt("name");

運行程序,會報錯:

Exception in thread "main" net.sf.json.JSONException: JSONObject["name"] is not a Boolean.

Exception in thread "main" net.sf.json.JSONException: JSONObject["name"] is not a number.這一類錯誤。

 

特別要注意的是{"age":23,"married":false,"name":"false"},其中沒帶""號的false是boolean類型,帶引號的是字符串類型。

還有就是大多數類型能夠轉換爲字符串類型,可是反過來就不行了。

 

(3)複雜數據類型

寫一個複雜點的bean

public class Student implements Serializable{
    private static final long serialVersionUID = 1L;
    private String sname;
    private Integer age;
    private Date birth;
    private List<String> courses;
    private Map<String,String> photo;
    private Emp emp;

而後,生成對象,給屬性賦值

    public static void main(String[] args) {
        Student s = new Student();
        List<String> sList = new LinkedList<String>();
        Map<String,String> photos = new HashMap<String,String>();
        Emp emp = new Emp();
        emp.setName("me");
        emp.setAge(10);
        emp.setMarried(false);
        
        sList.add("a");
        sList.add("b");
        
        photos.put("c", "c");
        photos.put("d", "d");
        
        s.setSname("EZ");
        s.setAge(23);
        s.setBirth(new Date());
        s.setCourses(sList);
        s.setPhoto(photos);
        s.setEmp(emp);
        
        JSONObject jsonObject = JSONObject.fromObject(s);
        System.out.println(jsonObject.toString());
        
        //jsonObject轉換爲javaBean        
        Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
        System.out.println(student.getSname() + ";" + student.getAge() + ";" +student.getBirth() + ";" + student.getCourses().get(1) + ";" + student.getPhoto().get("c") + ";" + student.getEmp());
    }

運行結果:

{"age":23,"birth":{"date":7,"day":2,"hours":17,"minutes":24,"month":6,"seconds":33,"time":1436261073641,"timezoneOffset":-480,"year":115},"courses":["a","b"],"emp":{"age":10,"married":false,"name":"me"},"photo":{"d":"d","c":"c"},"sname":"EZ"}
2015-7-7 17:24:33 net.sf.json.JSONObject toBean
信息: Property 'day' of class java.util.Date has no write method. SKIPPED.
2015-7-7 17:24:33 net.sf.json.JSONObject toBean
信息: Property 'timezoneOffset' of class java.util.Date has no write method. SKIPPED.
EZ;23;Tue Jul 07 17:24:33 CST 2015;b;c;com.vmaxtam.json.Emp@43b09468

 

雖然順利把數據轉換回去了,可是出現了警告信息,總讓人沒法安心下來。

若是仔細觀察,能夠發現,以上警告都是有關 java.util.Date 的警告,那麼Date類型該如何處理呢?

而且,留意   "birth":{"date":8,"day":3,"hours":11,"minutes":11,"month":6,"seconds":31,"time":1436325091564,"timezoneOffset":-480,"year":115},

你會發現這個格式的數據十分難懂,並且咱們通常只要用到yyyy-MM-dd這種格式。

 

二)Date類型

關於Date類型的轉換,咱們能夠經過轉換器來實現。

先寫一個轉換器:

public class JsonDateValueProcessor implements JsonValueProcessor {
    private String datePattern = "yyyy-MM-dd";

    public JsonDateValueProcessor() {
        super();
    }

    public JsonDateValueProcessor(String format) {
        super();
        this.datePattern = format;
    }

    @Override
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    @Override
    public Object processObjectValue(String key, Object value,
            JsonConfig jsonConfig) {
        return process(value);
    }

    private Object process(Object value) {
        try {
            if (value instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
                        Locale.UK);
                return sdf.format((Date) value);
            }
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            return "";
        }

    }

    public String getDatePattern() {
        return datePattern;
    }

    public void setDatePattern(String pDatePattern) {
        datePattern = pDatePattern;
    }
}

而後再進行測試:

    public static void main(String[] args) {
        Student s = new Student();
        s.setBirth(new Date());
        
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
                
        JSONObject jsonObject = JSONObject.fromObject(s,config);
        System.out.println(jsonObject.toString());
    }

最後輸出的結果

{"age":0,"birth":"2015-07-08","courses":[],"emp":null,"photo":null,"sname":""}

相關文章
相關標籤/搜索