美文网首页
JSON格式解析

JSON格式解析

作者: Crane_FeiE | 来源:发表于2018-09-26 07:12 被阅读0次

    样例JSON格式

    [
        {"id":"5", "version":"1", "name":"Clash of Clans"},
        {"id":"6", "version":"2", "name":"Boom Beach"},
        {"id":"5", "version":"1", "name":"Okey Google"}
    ]
    

    1.使用JsonObject解析

    还是以上文xml解析的activity为基础,将parseXml方法替换成parseJsonWithJSONObject方法

        private void parseJsonWithJSONObject(String responseString) {
            try {
                JSONArray array = new JSONArray(responseString);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jObject = array.getJSONObject(i);
                    String id = jObject.getString("id");
                    String name = jObject.getString("name");
                    String version = jObject.getString("version");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    

    2.使用Gson解析

    Gson是谷歌提供的用于解析Json数据的开源库,可以以十分简单的方式来解析Json数据

    基本用法

            Gson gson = new Gson(); //create a new Gson object;
            AppBean apps = gson.fromJson(responseString, AppBean.class); //parse an Json Object
            List<AppBean> appList = gson.fromJson(responseString
                    , new TypeToken<List<AppBean>>(){}.getType());  //parse an Json array
    

    Sample Code

        private void parseJsonWithGson(String responseString) {
            Gson gson = new Gson();
            //parse an Json array
            List<AppBean> appList = gson.fromJson(responseString, new TypeToken<List<AppBean>>(){}.getType());
            for(AppBean app : appList) {
                //do whatever you want with data
                Log.i("lyh", app.toString());
            }
        }
    

    相关文章

      网友评论

          本文标题:JSON格式解析

          本文链接:https://www.haomeiwen.com/subject/xoytoftx.html