Android以JSONOject和GSON两种方式解析json

json文件如下:

将获取到的json数据转化为String形式

OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://10.0.2.2/get_data.json")
                            .build();
                    Response response =client.newCall(request).execute();
                    String responseData = response.body().string();

以JSONObject方式解析:将获取的字符串转化为json数组,然后循环遍历这个数组。

private 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 version = jsonObject.getString("version");
                String name = jsonObject.getString("name");
                Log.i("JSONObject", "id is: "+id);
                Log.i("JSONObject", "version is: "+version);
                Log.i("JSONObject", "name is: "+name);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

以GSON方式:

首先依据json文件的形式建相应的类:

public class App
{
    private String id;
    private String version;
    private String name;
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

然后,新建一个Gson对象,利用TypeToken的方式将Data转成一个List并把这个List传入fromJson方法

private void parseJSONWithGSON(String jsonData){
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
        for(App app : appList){
            Log.i("GSON", "id is: "+app.getId());
            Log.i("GSON", "version is: "+app.getVersion());
            Log.i("GSON", "name is: "+app.getName());
        }
    }

猜你喜欢

转载自www.cnblogs.com/dengmin111/p/9063654.html