JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,它使得人們可以輕易地閱讀和編寫,同時也方便機器進行解析和生成。儘管 JSON 脫胎於 JavaScript 但其自己採用徹底獨立於程序語言的文本格式,是理想的數據交換方式。JSON 的官方 MIME
類型是 application/json
,文件擴展名是 .json
。javascript
JSON 存在兩種結構:html
{
(左括號)開始,}
(右括號)結束,數據結構爲 {key:value, key:value,...}
的鍵值對,key
表明對象的屬性,value
表明對應的屬性值,鍵與值中間包含一個:
(冒號),多個鍵值對之間使用,
(逗號)分隔。value
(值)的有序集合。一個數組以[
(左中括號)開始,]
(右中括號)結束。值與值之間使用,
(逗號)分隔。經過以上兩種結構能夠表示各類複雜結構。java
JavaScript JSON 對象示例:json
myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ "320", "X3", "X5" ] }, { "name":"Fiat", "models":[ "500", "Panda" ] } ] }
JSONObject 對象由一系列無序的鍵值對組成。具備 get 和 opt 方法用於按 key
(鍵)訪問 value
(值),同時提供 put 方法用於按 key
(鍵)添加或替換 value
(值)。toString() 方法生成 JSON 的字符串表示。api
Java 中值能夠是如下任何類型:Boolean, JSONArray, JSONObject, Number, String, JSONObject.NULL 對象。數組
The opt methods differ from the get methods in that they do not throw. Instead, they return a specified value, such as null.
使用 get 方法返回值時,若是找不到就拋出一個異常。須要咱們使用 try catch 語句或者 throw。數據結構
使用 opt 方法返回值時,若是找不到並不會拋出異常,而是返回友好的默認值。 oracle
例如:app
key
(鍵)不存在或者值的類型不匹配,則默認返回 null
,所以只需檢查它是否爲空,進而繼續執行函數的功能。一言以蔽之,對於獲取 JSON 中可選的值(鍵無關緊要,值可對可錯)推薦使用 opt 方法。函數
Method | Description |
---|---|
optJSONArray | Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not a JSONArray. |
optJSONObject | Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not a JSONObject. |
optString | Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is converted to a string. |
續表:
Method | Description |
---|---|
optBoolean | Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not Boolean.TRUE or the String "true". |
optDouble | Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. |
optInt | Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. |
optLong | Get an optional long value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. |
上述 opt 方法還提供帶有 defaultValue 參數的版本:
Type | Method |
---|---|
boolean | optBoolean(String key, boolean defaultValue) |
double | optDouble(String key, double defaultValue) |
int | optInt(String key, int defaultValue) |
long | optLong(String key, long defaultValue) |