简体   繁体   English

使用Gson解析列表对象json

[英]Parse list object json using Gson

i'm trying to parse Json with the google Gson library, but for the moment i can't get it to work ... 我正在尝试用谷歌Gson库解析Json,但目前我无法让它工作......

Here is the Json i'm supposed to get : 这是我应该得到的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"
            }
        ]
    }
 ]
}

Here are my models : 这是我的模特:

shoppingLists : 购物清单:

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 : 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;
}

Here is my AsyncTask which get the Json from the server : 这是我从服务器获取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);
    }
}
}

The exception "second" is always firing ... Log.i("infos", "model is null"); “second”异常总是触发... Log.i(“infos”,“model is null”); is also executed. 也被执行了。 if someone could help :) thank you ! 如果有人可以帮助:)谢谢! regards. 问候。

JSON

Add one more wrapper to your shoppingLists, as your jsonObject had shoppingLists as key and array of ShoppingListItem as value. 再向购物列表中添加一个包装器,因为您的jsonObject将shoppingLists作为键,并将ShoppingListItem数组作为值。 Also you need to annotate @SerializedName for ShoppingItems field because it is not matching with the key in Json. 此外,您还需要为ShoppingItems字段注释@SerializedName ,因为它与Json中的键不匹配。

Find below updated classes and parser 查找以下更新的类和解析器

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

Classes

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;
}

You don't have a list of shoppingLists items in the json - if my glasses don't fool me. 你没有json中的shoppingLists项目列表 - 如果我的眼镜不会欺骗我。 So changing: 如此改变:
List<shoppingLists> Obj = (List<shoppingLists>) gson.fromJson(all, new TypeToken<List<shoppingLists>>(){}.getType());

into: 成:

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

will not cause any runtime gson exceptions. 不会导致任何运行时gson异常。 Eventually you can wrap that single parsed obj into a List so it matches with your current code. 最终,您可以将单个解析的obj包装到List以便它与您当前的代码匹配。 For Example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM