JSON初體驗(一)

來源:互聯網
上載者:User

標籤:之間   image   info   存在   一點   pts   null 指標   com   system   

在學校的呆了一段時間,馬上又要回去工作了,不說了,我現在介紹一下json相關的內容

1.JSON資料格式(總的來說,json就是一個字串)
  1.整體結構
    String json1 = "{"id":12,"name":"Tom"}";
    String json2 = "[{"id":12,"name":"Tom"},{"id":12,"name":"Tom"}]";

  2.json對象
    a.json對象的結構:{key1:value1,key2:value2,key3:value3}

    b.key的資料類型:字串

    c.value的資料類型:
      1.數值
      2.字串
      3.null
      4.json數組[]
      5.json對象{}

    d.例子
      正確的:{“name”:"TOM","age":12}
      錯誤的:{"aa":"a",3}
  3.json數組
    a.json數組的結構:[value1,value2,value3]

    b.value的資料類型:
      1.數值
      2.字串
      3.null
      4.json數組[]
      5.json對象{}

    c.例子
      正確的:[1,"ab",[],{"n":132,“b”:"abc"}]
      錯誤的:[1,"a":3]

 

2.JSON解析方向
  1.將java對象(包含集合)轉換為json格式字串(在伺服器端應用)

  2.將json格式字串轉換為java對象,包含集合(在用戶端應用)

  3.json和java之間的轉換關係
    a.json對應java對象
    b.json數組與java對象構成的list相對應

3.JSON解析技術
  1.Android原生技術:
    特點:編程相對麻煩
    資料之間轉換(demo):
      a.將json格式的字串{}轉換為java對象

        API:
          JSONObject(String json):將json字串解析為json對象
          Xxx getXxx(String name):根據name,在json對象中得到對應的Value
          Xxx optXxx(String name):根據name,在json對象中得到對應的value
        注意:
          optXxx方法會在對應的key中的值不存在的時候返回一個Null 字元串或者返回
          你指定的預設值,但是getString方法會出現null 指標異常的錯誤

String json = "{\n" +"    \"id\":2,\n" +     "    \"name\":\"Tom\",\n" +     "    \"price\":12.3,\n" +"    \"imagePath\":\"http://www.baidu.com\"\n" +"}"JSONObject jsonObject = new JSONObject(json);int id = jsonObject.optInt("id");String name = jsonObject.optString("name");double price = jsonObject.optDouble("price");String imagePath = jsonObject.optString("imagePath");

      b.將json格式的字串[]轉換為java對象的List

        API:
          JSONArray(String json):將json字串解析為json數組
          int length():得到json數組中元素的個數
          Xxx getXxx(int index):根據下標得到json數組中對應的元素資料
          Xxx optXxx(int index):根據下標得到json數組中對應的元素資料
        注意:
          optXxx方法會在對應的key中的值不存在的時候返回一個Null 字元串或者返回
          你指定的預設值,但是getString方法會出現null 指標異常的錯誤

String json = "[\n" +"    {\n" +"        \"id\":1,\n" +     "        \"imagePath\":\"www.baidu.com\",\n" +"        \"name\":\"Tom1\",\n" +     "        \"price\":12.3\n" +"    },\n" +"    {\n" +"        \"id\":1,\n" +"        \"imagePath\":\"www.douban.com\",\n" +"        \"name\":\"Tom2\",\n" +"        \"price\":12.5\n" +"    }\n" +"]";List<First> list = new ArrayList<First>();JSONArray jsonArray = new JSONArray(json);for (int i = 0; i < jsonArray.length() ; i++) {    JSONObject jsonObject = jsonArray.getJSONObject(i);    if(jsonObject != null){  int id = jsonObject.optInt("id");  String imagePath = jsonObject.optString("imagePath");  String name =  jsonObject.optString("name");  Double price = jsonObject.optDouble("price");  First first = new First(id, name, price, imagePath);  list.add(first);}}for (int i = 0; i <list.size() ; i++) {  System.out.println(list.get(i).toString());}

  c.複雜json資料解析

String json = "{\n" +     "    \"data\":{\n" +"        \"count\":5,\n" +"        \"items\":[\n" +"            {\n" +"                \"id\":45,\n" +"                \"title\":\"堅果\"\n" +"            },\n" +"            {\n" +     "                \"id\":132,\n" +"                \"title\":\"炒貨\"\n" +     "            },\n" +"            {\n" +"                \"id\":166,\n" +"                \"title\":\"蜜餞\"\n" +"            },\n" +"            {\n" +"                \"id\":195,\n" +"                \"title\":\"果脯\"\n" +"            },\n" +"            {\n" +     "                \"id\":196,\n" +"                \"title\":\"禮盒\"\n" +"            }\n" +"        ]\n" +"    },\n" +"    \"rs_code\":\"1000\",\n" +"    \"rs_msq\":\"success\"\n" +"}";List<Second> list = new ArrayList<Second>();JSONObject jsonObject = new JSONObject(json);JSONObject data = jsonObject.optJSONObject("data");String rs_code = jsonObject.optString("rs_code");String rs_msq = jsonObject.optString("rs_msq");int count = data.optInt("count");JSONArray items = data.optJSONArray("items");for (int i = 0; i < items.length(); i++) {    JSONObject jj = items.getJSONObject(i);    int id = jj.optInt("id");    String title = jj.optString("title");    Second second = new Second(id,title);    list.add(second);
}

  d.特殊json資料解析

    FilmInfo類

public class FilmInfo {  private int code;   private List<FilmBean> list;   public int getCode() {     return code;   }   public void setCode(int code) {     this.code = code;   }   public List<FilmBean> getList() {     return list;   }   public void setList(List<FilmBean> list) {     this.list = list;   }   public static class FilmBean{     private String  aid;     private String author;     private int coins;     private String copyright;     private String create;     public String getAid() {       return aid;     }     public void setAid(String aid) {       this.aid = aid;     }     public String getAuthor() {       return author;      }      public void setAuthor(String author) {        this.author = author;      }      public int getCoins() {        return coins;      }      public void setCoins(int coins) {        this.coins = coins;      }      public String getCopyright() {        return copyright;      }      public void setCopyright(String copyright) {        this.copyright = copyright;      }      public String getCreate() {        return create;      }      public void setCreate(String create) {        this.create = create;      }      @Override      public String toString() {        return "FilmBean{" +                 "aid=‘" + aid + ‘\‘‘ +                 ", author=‘" + author + ‘\‘‘ +                 ", coins=" + coins +                 ", copyright=‘" + copyright + ‘\‘‘ +                 ", create=‘" + create + ‘\‘‘ +                 ‘}‘;        }
} @Override
public String toString() {   return "FilmInfo{" + "code=" + code + ", list=" + list + ‘}‘; }}

此時對json進行分析

  

  String json = "{\n" +        "    \"code\":0,\n" +        "    \"list\":{\n" +"        \"0\":{\n" +        "            \"aid\":\"6008965\",\n" +"            \"author\":\"嗶哩嗶哩番劇\",\n" +"            \"coins\":170,\n" +"            \"copyright\":\"Copy\",\n" +"            \"create\":\"2016-08-25 21:34\"\n" +"        },\n" +"        \"1\":{\n" +"            \"aid\":\"6008938\",\n" +"            \"author\":\"嗶哩嗶哩番劇\",\n" +"            \"coins\":404,\n" +r"            \"copyright\":\"Copy\",\n" +"            \"create\":\"2016-08-25 21:33\"\n" +"        }\n" +        "    }\n" +"}";FilmInfo filmInfo = new FilmInfo();JSONObject jsonObject = new JSONObject(json);int code = jsonObject.optInt("code");filmInfo.setCode(code);List<FilmInfo.FilmBean> filmList = new ArrayList<FilmInfo.FilmBean>();filmInfo.setList(filmList);JSONObject list = jsonObject.optJSONObject("list");for (int i = 0; i <list.length() ; i++) {JSONObject jsonObject1 = list.optJSONObject(i + "");String aid = jsonObject1.optString("aid");String author = jsonObject1.optString("author");int coins = jsonObject1.optInt("coins");String copyright = jsonObject1.optString("copyright");String create = jsonObject1.optString("create");FilmInfo.FilmBean filmBean = new FilmInfo.FilmBean();filmBean.setAid(aid);filmBean.setAuthor(author);filmBean.setCoins(coins);filmBean.setCopyright(copyright);filmBean.setCreate(create);filmList.add(filmBean);}System.out.println(filmInfo);

 最後在補充一點,這裡面的org.json.jsonObject的maven為

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>

JSON初體驗(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.