JSON数据

来源:互联网 发布:retrofit post json 编辑:程序博客网 时间:2024/06/07 07:03

一:JSON的简介

     JSON:JvavScript对象表示法(JavaScript Object Notation)。

     JSON是存储和交换文本信息的语法。

                 .  JSON是轻量级的文本数据交换格式

                 .  JSON独立于语言和平台

                 .  JSON具有自我描述性、更易读懂


     类似XML,比XML更小、更快、更易解析。

                . 没有结束标签

               .  更短

               . 读写速度更快

               . 不使用保留字


      JSON语法是JavaScript对象表示法语法的子集

               .  数据在采用键值对的方式

               .  数据由逗号分隔

               . 花括号保存对象

               .  方括号保存数组


       JSON的值可以是:

               .  数字(整数或浮点数)

               . 字符串(在双引号中)

               .  逻辑值(true或false)

               .  数组(在方括号中)

               .  对象(在花括号中)

               .  null


       JSON数组在方括号中书写,数组可以有多个对象:

         


       JSON对象在花括号中书写,对象可以包含多个键值对

         


二:读取JSON格式数据


JSON数据如下:

 {    "cat": "it",    "languages": [        {            "id": 1,            "ide": "Eclipse"        },        {            "id": 2,            "ide": "Xcode"        }    ]}


生成以上的JSON数据:

   try {            JSONObject root = new JSONObject();            root.put("cat","it");            JSONObject lan1 = new JSONObject();            lan1.put("id",1);            lan1.put("ide","Eclipse");            JSONObject lan2 = new JSONObject();            lan2.put("id",2);            lan2.put("ide","Xcode");            JSONArray jsonArray=new JSONArray();            jsonArray.put(lan1);            jsonArray.put(lan2);            root.put("languages",jsonArray);                        System.out.println(root.toString());  } catch (JSONException e) {            e.printStackTrace();      }


解析:

   

      String s = "{\"cat\":\"it\",\"languages\":[{\"id\":1,\"ide\":\"Eclipse\"},{\"id\":2,\"ide\":\"Xcode\"}]}";        try {            JSONObject jsonObject = new JSONObject(s);            JSONArray jsonArray = jsonObject.getJSONArray("languages");            for (int i = 0; i < jsonArray.length(); i++) {                JSONObject lan = jsonArray.getJSONObject(i);                int id = lan.getInt("id");                String ide = lan.getString("ide");                System.out.println("id:" + id + "-----ide:" + ide);            }        } catch (JSONException e) {            e.printStackTrace();        }



  输出结果为:

    System.out: id:1-----ide:Eclipse
    System.out: id:2-----ide:Xcode