2017-05-04 174 views
0

当我使用如何从Java中的JSONObject获取值?

jitem.getString("firstitem"); 

jitem.getJSONObject("firstitem"); 

jitem.get("firstitem"); 

以下是代码片段我试图解析JsonArray并获得其价值,但我gettign错误。

JSONArray arr_items = new JSONArray(str); 
     if(arr_items!=null && arr_items.size()>0){ 

      for(int i=0;i<arr_items.size();i++){ 
      JSONObject jitem = arr_items.getJSONObject(i);//works fine till here 
      jitem.getString("firstitem"); //throws exception here 
      } 

这是我解析

[{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"[email protected]","fourthitem":"jkksdjklsfjskj"}] 

我在做什么错JSONArray?如何通过使用键来获取这些值?

更新:说明该数组及其参数根本不为空。他们都有有效的价值。

+0

什么是例外? – Henry

+0

你正在使用哪个json库?既然你有org.json和org.json.simple的混合方法 –

+0

@SachinGupta我正在使用org.apache.commons.json –

回答

0

首先检查arr_items不是空的。 然后,尝试用的try/catch周围的片段:

try { 
     your snippet 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
+0

这是如何解决问题的?它避免了一个例外,但仍然没有价值。 – Henry

+0

在Android Studio中,如果我不尝试围绕/捕获这个类型片断,编辑给予警告,我必须得围绕着它。也许,他可以试试 –

0

检查以下

String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'[email protected]','fourthitem':'jkksdjklsfjskj'}]"+ "}"; 
    JSONObject myjson = new JSONObject(json); 
    JSONArray the_json_array = myjson.getJSONArray("array"); 

    int size = the_json_array.length(); 
// ArrayList<JSONObject> arrays = new ArrayList<JSONObject>(); 
    for (int i = 0; i < size; i++) { 
     JSONObject another_json_object = the_json_array.getJSONObject(i); 
    // arrays.add(another_json_object); 
     System.out.println(another_json_object.get("firstitem")); 
    } 

它需要一些数组名称,以便追加数组名吧,如果你想没有它,你必须添加GSON 。