使用Gson解析列表对象json

时间:2014-03-22 14:36:25

标签: java android json gson

我试图用谷歌Gson图书馆解析Json,但目前我无法让它工作......

这是我应该得到的Json:

{
"shoppingLists": [
    {
        "ShoppingList": {
            "id": "51",
            "name": "loool",
            "created": "2014-03-22 13:03:22",
            "modified": "2014-03-22 13:03:22"
        },
        "ShoppingItem": [
            {
                "id": "24",
                "shopping_item_category_id": "19",
                "name": "Biscuits",
                "description": "",
                "created": "2014-02-05 17:43:45",
                "modified": "2014-02-05 17:43:45",
                "category_name": "Confiseries \/ Gouters"
            },
            {
                "id": "25",
                "shopping_item_category_id": "19",
                "name": "Snickers",
                "description": "",
                "created": "2014-02-05 17:44:08",
                "modified": "2014-02-05 17:44:08",
                "category_name": "Confiseries \/ Gouters"
            },
            {
                "id": "26",
                "shopping_item_category_id": "19",
                "name": "C\u00e9reales",
                "description": "",
                "created": "2014-02-05 17:44:57",
                "modified": "2014-02-05 17:44:57",
                "category_name": "Confiseries \/ Gouters"
            }
        ]
    }
 ]
}

以下是我的模特:

购物清单:

public class shoppingLists {
        public ShoppingList ShoppingList;
        public List<ShoppingItem> ShoppingItems;
}

ShoppingList:

public class ShoppingList {
public int id;
public String name;
public String created;
public String modified;
}

ShoppingItem:

public class ShoppingItem {
public int id;
public int shopping_item_category_id;
public String name;
public String description;
public String created;
public String modified;
public String category_name;
}

这是我从服务器获取Json的AsyncTask:

public class APIRetrieveLists extends AsyncTask<APIRequestModel, Void, List<shoppingLists>>{

SQLHelper _sqlHelper = null;
Context _context;
ProgressBar _pb;

public APIRetrieveLists(Context context, ProgressBar pb){
    this._context = context;
    this._pb = pb;
}


@Override
protected void onPreExecute(){
}

@Override
protected void onPostExecute(List<shoppingLists> model){
    this._sqlHelper = new SQLHelper(this._context);
    if (model != null){
        for (shoppingLists cn : model){
            Log.i("infos", "list's name => " + cn.ShoppingList.name);
        }
    }else{
        Log.i("infos", "model is null");
    }
}

@Override
protected List<shoppingLists> doInBackground(APIRequestModel... arg0) {
    APIRequestModel model = arg0[0];
    try
    {
        try
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("access_token", model.getToken()));
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://apiurl/index.json");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httppost);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String s = "";
            String all = "";
            while ((s = reader.readLine()) != null){
                all += s;
            }
            Gson gson = new Gson();
            List<shoppingLists> Obj = (List<shoppingLists>) gson.fromJson(all, new TypeToken<List<shoppingLists>>(){}.getType());
            return (Obj);
        } 
        catch (ClientProtocolException e) {
            Log.i("infos", "first");
            return (null);
        } 
    }
    catch (Exception e){
        Log.i("infos", "second");
        return (null);
    }
}
}

例外&#34;秒&#34;总是开火...... Log.i(&#34; infos&#34;,&#34; model为null&#34;);也被执行了。 如果有人可以帮助:) 谢谢 ! 问候。

json

2 个答案:

答案 0 :(得分:2)

在shoppingLists中再添加一个包装器,因为jsonObject将shoppingLists作为键,并将ShoppingListItem数组作为值。此外,您还需要为ShoppingItems字段注释@SerializedName,因为它与Json中的密钥不匹配。

查找以下更新的类和解析器

Gson gson = new Gson();
FinalClass myObj = gson.fromJson(jsonString, FinalClass.class);

public class FinalClass {
    public ArrayList<ShoppingListItem> shoppingLists;
}

public class ShoppingListItem {
    public ShoppingList ShoppingList;
    @SerializedName("ShoppingItem")
    public List<ShoppingItem> ShoppingItems;
}

public class ShoppingList {
    public int id;
    public String name;
    public String created;
    public String modified;
}

public class ShoppingItem {
   public int id;
   public int shopping_item_category_id;
   public String name;
   public String description;
   public String created;
   public String modified;
   public String category_name;
}

答案 1 :(得分:1)

如果我的眼镜不能欺骗我,你在json中没有shoppingLists项目列表。如此改变:
List<shoppingLists> Obj = (List<shoppingLists>) gson.fromJson(all, new TypeToken<List<shoppingLists>>(){}.getType());

成:

shoppingLists obj = gson.fromJson(all, shoppingLists.class);

不会导致任何运行时gson异常。最终,您可以将单个已解析的obj包装到List中,以便它与您当前的代码匹配。例如:

shoppingLists obj = gson.fromJson(all, shoppingLists.class);
ArrayList<shoppingLists> result = new ArrayList<shoppingLists>();
result.add(obj);
return result;