我何时获取数据时如何避免Json数组

时间:2014-10-08 13:54:25

标签: java json

我在java中获取Json数据,而我的Json具有不同的结构并且并不总是相同。示例:

{"0":{"id"="255",name="example"},"1":{"news_id":"47221","news_infos":{"title":"test","date":"2014-05-14 17:44:02","shared":"47"},"website":"test.it"},"3":{"id"="55885",name="foo"}}

这只是一个例子。我想知道的是我如何跳过第二个,我们假设第二个是JsonArray。 这是我在java中所做的一个例子;

 for (int i = 0; i < jObj.length() ; i++) {
                try {
                    JSONObject obj = jObj.getJSONObject(i); //Suppose that every entry in the Json is an object and not a JsonArray.
                    if (!obj.isNull("titrenews")) {
                        Home home = new Home();
                        Log.i("Infos","Yes");
                        home.setNomC(obj.getString("titrenews"));
                        home.setPhotoAr(photoNews);
                        home.setText(obj.getString("textnews"));
                        home.setNbrSick(obj.getString("sicks"));

                        homeList.add(home);

                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
             }

总结问题我有一个json数据。由JsonObject和JsonArray组成,我想要的是跳过jsonArray条目并避免它

所以任何解决方案都可以!

1 个答案:

答案 0 :(得分:0)

尝试这种方法:

for (Object obj : jObj) {
    if (obj instanceof JSONObject){
        //do something
    }
    else if (obj instanceof JSONArray){
      continue;//skip
    }
}