美文网首页
解析json格式文件

解析json格式文件

作者: 墨染草 | 来源:发表于2018-09-28 16:09 被阅读5次

package example.com.networktest.utility;

import android.nfc.Tag;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import example.com.networktest.bean.App;

public class ParseJSON {

private static final String TAG = "我是ParseJSON";

    /* 使用JSONObject 对象来解析JSON格式数据 */
    public static void ParseJsonWithJSONObject(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 = jsonObject.getString("version");
                Log.d(TAG+" JSONObject", "id is :" + id);
                Log.d(TAG+" JSONObject", "name is :" + name);
                Log.d(TAG+" JSONObject", "version is :" + version);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
/* 使用GSON来解析JSON格式数据 */
public static void ParseJsonWithGSON(String jsonData) throws JsonSyntaxException {
    Gson gson = new Gson();
    List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {
    }.getType());
    for (App app : appList) {
        Log.d(TAG, "id is :" + app.getId());
        Log.d(TAG, "name is :" + app.getName());
        Log.d(TAG, "version is :" + app.getVersion());
    }
} }

相关文章

网友评论

      本文标题:解析json格式文件

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