android用JSONObject和JSONArray解析json格式数据

来源:互联网 发布:侠盗飞车3罪恶都市mac 编辑:程序博客网 时间:2024/04/30 19:42

什么是json

我们在android网络传输中经常用到的xml和json,其中json英文名是JavaScript Object Notation,翻译过来也就是js对象表示法。虽然他不如xml直观但是因为它轻量便捷相对于xml来说省流量,所以现在大多数都是用json来传输网路数据。

json结构

首先json的取值可以为:
数字(整数或者浮点数)
字符串(在双引号内)
逻辑值(true 或 false)
数组(使用方括号[]包围)
对象( 使用花括号{}包围)
null
而JSON中有且只有两种结构:对象和数组。
先以下为例:
其中对象有status,error,count,data
相对于status=200,error=“”,count=1,而data对象里面又有两个数组,每个数组有4个对象

{"status": 200,    "error": "",    "count": 2,    "data": [        {            "fid": 221,            "kid": 34,            "filename": "黄贯中 - 海阔天空",            "singername": "黄贯中",        },         {            "fid": 229,            "kid": 341,            "filename": "黄贯中2- 海阔天空",            "singername": "黄贯中2",        },    ]}

使用JSONObject和JSONArray解析

我们使用JSONObject和JSONArray解析上面代码中的数组,相信介绍我在代码中也注明

 public void getInformation(String jonString)            throws Exception {//获得json对象        JSONObject dataOfJson =new JSONObject(jonString);        /*获得对象count的值,其中有optxxx和getxxx方法,但当opt对应的cout没有值的时候它会返回空值所以不会报错,推荐用这个*/        int number=dataOfJson.optInt("count");        //jsonarray解析data数组        JSONArray results=dataOfJson.optJSONArray("data");        JSONObject[] b= new JSONObject[2];        //获取data数组一        b[0]=results.getJSONObject[0];        //获得data数组二         b[1]=results.getJSONObject[1];         //获得数组一中的fid对象       int fid1=b[0].getInt("fid");       int kid1=b[0].getInt("kid");       String filename1=b[0].getInt("filename");       String singername1=b[0].getInt("singername");       int fid2=b[1].getInt("fid");       int kid2=b[1].getInt("kid");       String filename2=b[1].getInt("filename");       String singername2=b[1].getInt("singername");    }

其实解析json还有很多重方法比如google的GSON,android中的JsonReader和JsonWriter等,希望这篇文章对大家有用,同时也欢迎大家指正。(只希望每天进步一点点0.0)

0 0
原创粉丝点击