JSONObject 和 JSONArray 的區別和用法

JSONObject 和 JSONArray 的數據表現形式不一樣:

JSONObject的數據是用 {  } 來表示的,例如: { "id" : "1", "name" : "zhuzhu", "age" : "22", "sex" : "男"} json

JSONArray 是JSONObject組成的數組,是{ }外層套了一個 [ ] ,裏邊有一個或者多個 { } ,好比  [ {  "id" : "1", "name" : "zhuzhu", "age" : 「22", "sex" : "男" } ] 數組

總結一下 JSONObject 外層是 { },JSONArray外層是 [ ] 
你們處理數據的時候必定要看清楚數據格式,分別使用不一樣的方法來處理數據,不然是會直接轉換異常的!

下邊簡單來一個JSONObject小例子:spa

引入的包有:code

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;blog

@Test
public
void testJSONObject(){ String str ="{id:\"1\",name:\"zhuzhu\",age:\"22\",sex:\"男\"}"; JSONObject jsonObject = JSONObject.parseObject(str); Integer id = jsonObject.getInteger("id"); String name = jsonObject.getString("name"); String age = jsonObject.getString("age"); String sex = jsonObject.getString("sex"); System.out.println("我是"+name+"我今年"+age+"歲啦,個人性別是"+sex); }

 

  輸出爲 :  我是zhuzhu我今年22歲啦,個人性別是男get

再簡單來一個JSONArray 的例子:ast

@Test
public
void testJSONArray(){ String str = "[{\"id\":\"1\",\"name\":\"zhuzhu\",\"age\":\"22\",\"sex\":\"男\"}]"; JSONArray jsonArray =JSON.parseArray(str); Integer id = null; String name = null ; String age = null ; String sex = null ; for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); id = jsonObject.getInteger("id"); name = jsonObject.getString("name"); age = jsonObject.getString("age"); sex = jsonObject.getString("sex"); } System.out.println("我是"+name+"我今年"+age+"歲啦,個人性別是"+sex); }

輸出爲 :  我是zhuzhu我今年22歲啦,個人性別是男class

 

好了 這就結束了,但願能幫到你們,這裏也有不少不全面的地方,只是給一種簡單的參考,若有問題請批評指出 ,謝謝test

相關文章
相關標籤/搜索