android 解析json数据格式

来源:互联网 发布:香港有淘宝网吗 编辑:程序博客网 时间:2024/04/26 06:40

android 解析json数据的两个方法分享:

一.简单解析

{"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}

分析代码如下:

                int res = 0;                 res = httpClient.execute(httpPost).getStatusLine().getStatusCode();                 if (res == 200) {                     /*                      * 当返回码为200时,做处理                      * 得到服务器端返回json数据,并做处理                      * */                     HttpResponse httpResponse = httpClient.execute(httpPost);                     StringBuilder builder = new StringBuilder();                     BufferedReader bufferedReader2 = new BufferedReader(                             new InputStreamReader(httpResponse.getEntity().getContent()));                     String str2 = "";                     for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2                             .readLine()) {                         builder.append(s);                     }                     Log.i("cat", ">>>>>>" + builder.toString());                 JSONObject jsonObject = new JSONObject(builder.toString()) .getJSONObject("userbean");                 String Uid;                 String Showname;                 String Avtar;                 String State;                 Uid = jsonObject.getString("Uid");                 Showname = jsonObject.getString("Showname");                 Avtar = jsonObject.getString("Avtar");                 State = jsonObject.getString("State");

二.带有数组的解析方法:


代码如下:

JSONObject jsonObject = new JSONObject(jsonString).getJSONObject("errorcode");errorcode = jsonObject.getString("errorcode");code = Integer.parseInt(errorcode);DicktAdapter.items.clear();if (code == 0) {JSONObject jsonObject1 = new JSONObject(jsonString).getJSONObject("data");JSONArray jsonArray = jsonObject1.getJSONArray("dick");for (int i = 0; i < jsonArray.length(); i++) {            JSONObject jsonDick = (JSONObject)jsonArray.opt(i);     dick = new Dick();    dick.setContent(jsonDick.getString("content"));    dick.setFrom(jsonDick.getString("from"));    dick.setTypeid(jsonDick.getString("typeid"));    dick.setErrorcode((Integer.parseInt(jsonDick.getString("errorcode"))));    adapter.addItems(dick);}}