org.json.JSONObject $ 1类型的'json key object'的值null无法转换为JSONObject

时间:2018-05-30 04:34:50

标签: android json

我正在尝试解析这个JSON:

{
  "data": [{
  "name": "Griya Legita",
  "is_broken": false,
  "is_repaired": false,
  "is_ok": true,
  "asset_parent": null
},
{
    "name": "4th Floor",
    "is_broken": true,
    "is_repaired": false,
    "is_ok": false,
    "asset_parent": {
      "name": "Buni Building",
      "is_broken": true,
      "is_repaired": false,
      "is_ok": false
    }
  }]
}

此JSON在JSON数组中有一个JSON对象。但是当我调用JSON对象时,它表示它无法转换。

这是我尝试过的代码:

class daftarAset extends AsyncTask < String, String, String > {
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      pDialog = new ProgressDialog(getActivity());
      pDialog.setMessage("LOADING...");
      pDialog.setIndeterminate(false);
      pDialog.setCancelable(true);
      pDialog.show();
    }

    @Override
    protected String doInBackground(String...params) {
      String link_url = "https://example.com/api/assets";
      HttpHandler sh = new HttpHandler();
      String json = sh.makeServiceCall(link_url);

      Log.e(TAG, "Response from url: " + json);
      if (json != null) {
        try {
          JSONObject jsonObject = new JSONObject(json);
          JSONArray data = jsonObject.getJSONArray("data");
          for (int i = 0; i < data.length(); i++) {
            JSONObject ar = data.getJSONObject(i);
            String aset = ar.getString("name");

            JSONObject parent = ar.getJSONObject("asset_parent");
            String nama = parent.getString("name");
            HashMap map = new HashMap();
            map.put(in_aset, aset);
            map.put(in_ruang, nama);
            data_map.add(map);
          }
        } catch (final JSONException e) {
          Log.e(TAG, "Json parsing error: " + e.getMessage());
          getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
              Toast.makeText(getActivity().getApplicationContext(),
                "Json parsing error: " + e.getMessage(),
                Toast.LENGTH_LONG).show();
            }
          });
        }
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            list = (ListView) getView().findViewById(R.id.baik_list);
            adapter = new AssetsAdapter(getActivity(), data_map);
            list.setAdapter(adapter);
            setListViewHeightBasedOnChildren(list);

          }
        });
      }
      return null;
    }

    @Override
    protected void onPostExecute(String s) {
      pDialog.dismiss();
    }

我不知道我的代码出了什么问题。我正在关注this tutorial,我觉得它必须正确,但它有一个错误,因为JSON无法转换。

这是我的错误:

W/System.err: org.json.JSONException: Value null at asset_parent of type org.json.JSONObject$1 cannot be converted to JSONObject
              at org.json.JSON.typeMismatch(JSON.java:100)
              at org.json.JSONObject.getJSONObject(JSONObject.java:613)
              at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:188)
              at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:162)
              at android.os.AsyncTask$2.call(AsyncTask.java:292)
              at java.util.concurrent.FutureTask.run(FutureTask.java:237)
              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
              at java.lang.Thread.run(Thread.java:818)

4 个答案:

答案 0 :(得分:2)

首先确保JSONObject包含asset_parent键,并且相应的键值不为空。然后检索值JSONObject

使用此代码:

      JSONObject jsonObject = new JSONObject(json);
      JSONArray data = jsonObject.getJSONArray("data");
      for (int i = 0; i < data.length(); i++) {
        JSONObject ar = data.getJSONObject(i);
        String aset = ar.getString("nama");

        HashMap map = new HashMap();
        map.put(in_aset, aset);

        if(ar.has("asset_parent") && !ar.isNull("asset_parent") ){
           JSONObject parent = ar.getJSONObject("asset_parent");
           String nama = parent.getString("nama");
            map.put(in_ruang, nama );
        }else{
             map.put(in_ruang, null );
        }

         Log.i("Test", "Map: " + map.toString()); 
         data_map.add(map); 
          ................ 
          .............
      }

希望它能解决您的问题。 让我知道你的问题已经解决了。

答案 1 :(得分:0)

检查对象是否可用,如下所示

if(ar.optJSONObject("asset_parent")) {
   if(ar.getJSONObject("asset_parent") != null) {
       //process the object
   }
}

答案 2 :(得分:0)

尝试一下

if(mJsonObject.has("Data") && !mJsonObject.isNull("Data") ) {
  // code here
}

答案 3 :(得分:-1)

   public void get_user_details(){
        StringRequest stringRequest = new StringRequest( Request.Method.GET,User_Details_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.e("Response",""+response);
                            JSONObject obj = new JSONObject(response);
                            JSONArray user_holder = obj.getJSONArray("User_holder");
                            JSONObject user = user_holder.getJSONObject(0);
                            user_id=user.getString("id");
                            user_name=user.getString("user_name");
                            user_password=user.getString("user_password");
                            user_emailid=user.getString("user_email");
                            PreferenceUtils.saveEmail(user_emailid,Register_Page.this);
                            PreferenceUtils.saveUsername(user_name,Register_Page.this);
                            PreferenceUtils.savePassword(user_password,Register_Page.this);
                            PreferenceUtils.saveUserid(user_id,  Register_Page.this);
                            PreferenceUtils.saveLocalValue(localValue,  Register_Page.this);
                            sharedPreferences.writeLginStastu(true);
                            if(PreferenceUtils.getEmail(Register_Page.this)!=null || !PreferenceUtils.getEmail(Register_Page.this).equals("")){
                                startActivity(new Intent(Register_Page.this, CongoCoin.class));
                                sharedPreferences.writeLginStastu(true);
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e("User_json",""+e.toString());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }