如何从Java中获取JSONObject的值?

时间:2017-05-04 11:12:41

标签: java arrays json string converter

我正在尝试解析JsonArray并获取其值,但是当我使用

时我遇到了错误
   jitem.getString("firstitem"); 

  jitem.getJSONObject("firstitem");

 jitem.get("firstitem");

以下是代码段。

  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
            }

这是我正在解析的JSONArray

 [{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"fdgfdgdf@sjhasjkdsha.com","fourthitem":"jkksdjklsfjskj"}]

我做错了什么?如何使用键获取这些值?

更新:注意此数组及其参数根本不为空。他们都有有效的价值观。

2 个答案:

答案 0 :(得分:0)

首先检查arr_items不为空。 然后,尝试使用try / catch包围您的代码段:

try {
       your snippet

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

答案 1 :(得分:0)

检查以下

String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'fdgfdgdf@sjhasjkdsha.com','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。