Android 对简单的 json 解析

 

Android 解析 JSON

要解析 JSON 数据,首先得先拿到 JSON 数据,我拿到的数据是这样的 {"msg":"请登陆","code":-999,"data":xxx}

1、使用JSONObject来解析JSON数据

    /**
     * JSON解析方法
     */
    protected void JSONAnalysis(String string) {
        JSONObject object = null;
        try {
            object = new JSONObject(string);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /**
         * 在你获取的string这个JSON对象中,提取所需要的信息
         */
        String msg = object.optString("msg");
        String code = object.optString("code");
        String data = object.optString("data");

        weatherResult = "msg:" + msg + "\ncode:" + code + "\ndata:" + data;
        textView.setText(weatherResult);
    }

JSONObject object = new JSONObject(string);  将Json字符串解析成Json对象。

 

2、解析Json数组

JSONArray(String json);将json字符串解析成json数组;

private void JSONAnalysis(String JsonData) {
    try{
        JSONArray jsonArray = new JSONArray(jsonData);
        for (int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String id = jsonObject.getString("id");
            String name = jsonObject.getString("name");
            String version = jsonObect.getString("version");
 
            System.out.println("id" + id + ";name" + name + ";version" + version);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

定义一个JSON数组,用于将服务器返回的数据传入到一个JSONArray对象中; 然后循环遍历这个JSONArray,从中取出每一个元素(JSONObject对象),接下来只需调用getString()方法即可将数据取出。

 

3、用Gson解析JSON

请参考:https://blog.csdn.net/qq_29269233/article/details/53352668

使用该方法解析JSON数据,首先需要添加GSON的jar包;

下载地址是:https://mvnrepository.com/artifact/com.google.code.gson/gson

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章