首页 > 解决方案 > 如何解析json数据Android

问题描述

如何将具有相同标题的系列解析为一个数组列表

所以我得到了第 1 季和第 2 季的标题名称

最好的方法是什么

我的 Json 数据

{
"series":[
{
"title":"Jumping cat", "genre":"comedy", "year":2018, "season":1, "imdb":7, "info":"comdey series", "episodes":10, "cover":"poster" }, {
"title":"Jumping cat", "genre":"comedy", "year":2019, "season":2, "imdb":7, "info":"comdey series", "episodes":11, "cover":"poster" } ] }

标签: androidjsonandroid-volley

解决方案


以下代码将创建一个带有字符串键和 ArrayList 值的“ HashMap ”。ArrayList 包括每个系列的模型:

try{
    JSONObject reader = new JSONObject(str);
    JSONArray array = reader.optJSONArray("series");
    HashMap<String, ArrayList<YourModel>> map =  new HashMap<>();
    for(int i=0;i<array.length();i++){
        JSONObject innerObject = array.getJSONObject(i);
        if(map.get(innerObject.getString("title")) != null){ // check if the title already exists, then add it to it's list
            ArrayList<YourModel> arrayList = map.get(innerObject.getString("title"));
            arrayList.add(new YourModel(innerObject));
        }else{ // if the title does not exist, create new ArrayList
            ArrayList<YourModel> arrayList = new ArrayList<>();
            arrayList.add(new YourModel(innerObject));
            map.put(innerObject.getString("title"),arrayList);
        }
    }
}catch (JSONException e){
    // Do error handling
}

推荐阅读