2017-01-16 118 views
-3

嗨,大家好,我不知道爲什麼,但我得到這個錯誤:JSONArray cannot be converted to JSONObject問題與JSONArray無法轉換爲JSONObject

我向你展示我的代碼!我希望你能幫助我!在此先感謝大家!我們是JSON

主要活動:

public class MainActivity extends AppCompatActivity { 

    private String TAG = MainActivity.class.getSimpleName(); 

    private ProgressDialog pDialog; 
    private ListView lv; 

    // URL to get contacts JSON 
    private static String url = " http://v1.tvguideapi.com/programs?channels[]=2161&channels[]=2162&start=1484598600&stop=1484605799"; 
    //private static String url = "http://api.androidhive.info/contacts/"; 

    ArrayList<HashMap<String, String>> contactList; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     contactList = new ArrayList<>(); 

     lv = (ListView) findViewById(R.id.list); 

     new GetContacts().execute(); 
    } 

    /** 
    * Async task class to get json by making HTTP call 
    */ 
    private class GetContacts extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      HttpHandler sh = new HttpHandler(); 

      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url); 

      Log.e(TAG, "Response from url: " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        //JSONObject jsonObj = new JSONObject(jsonStr); 
        JSONObject jsonObj = new JSONObject(jsonStr); 


        // Getting JSON Array node 
        JSONArray contacts = jsonObj.getJSONArray("programs"); 
        // JSONArray contacts = jsonObj.getJSONArray("contacts"); 


        // looping through All Contacts 
        for (int i = 0; i < contacts.length(); i++) { 
         JSONObject c = contacts.getJSONObject(i); 

        /*  String id = c.getString("id"); 
         String name = c.getString("name"); 
         String email = c.getString("email"); 
         String address = c.getString("address"); 
         String gender = c.getString("gender"); 

         // Phone node is JSON Object 
         JSONObject phone = c.getJSONObject("phone"); 
         String mobile = phone.getString("mobile"); 
         String home = phone.getString("home"); 
         String office = phone.getString("office");*/ 

         String title=c.getString("title"); 

         // tmp hash map for single contact 
         HashMap<String, String> contact = new HashMap<>(); 

         // adding each child node to HashMap key => value 
         /* contact.put("id", id); 
         contact.put("name", name); 
         contact.put("email", email); 
         contact.put("mobile", mobile);*/ 
         contact.put("title",title); 

         // adding contact to contact list 
         contactList.add(contact); 
        } 
       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG) 
            .show(); 
         } 
        }); 

       } 
      } else { 
       Log.e(TAG, "Couldn't get json from server."); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Couldn't get json from server. Check LogCat for possible errors!", 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(
        /* MainActivity.this, contactList, 
        R.layout.list_item, new String[]{"name", "email", 
        "mobile"}, new int[]{R.id.name, 
        R.id.email, R.id.mobile});*/ 
        MainActivity.this, contactList, 
        R.layout.list_item, new String[]{"title"}, new int[]{R.id.title}); 

      lv.setAdapter(adapter); 
     } 

    } 
} 

JSON:

[ 
    { 
    "id": "18879971", 
    "start": "2017-01-16 20:20:00", 
    "stop": "2017-01-16 22:30:00", 
    "lang": "", 
    "title": "Il Collegio</td>", 
    "subtitle": "", 
    "description": "", 
    "category": "", 
    "channel_id": "2162", 
    "icon": null, 
    "ts_start": 1484598000, 
    "ts_stop": 1484605800 
    }, 
    { 
    "id": "18879856", 
    "start": "2017-01-16 20:25:00", 
    "stop": "2017-01-16 22:40:00", 
    "lang": "", 
    "title": "I Bastardi di Pizzofalcone", 
    "subtitle": "", 
    "description": "Ep.3 - In un fatiscente condominio di Pizzofalcone viene rinvenuto il cadavere di una camariera. Le indagini della squadra portano al marito della donna, ma per Lojacono il caso si complica ulteriormente.", 
    "category": "", 
    "channel_id": "2161", 
    "icon": null, 
    "ts_start": 1484598300, 
    "ts_stop": 1484606400 
    } 
] 
+1

的'jsonStr'是'JSONArray'代替'JSONObject' –

+0

,所以我必須寫的嗎? JSONArray jsonObj = new JSONArray(jsonStr); – Markus

+1

是的,刪除'JSONObject jsonObj = new JSONObject(jsonStr);''和'JSONArray contacts = jsonObj.getJSONArray(「programs」);'行並寫入'JSONArray contacts = new JSONArray(jsonStr);' –

回答

1

你應該用你JSON數組。

你有[{},{}]格式這裏[]顯示JsonArray和{}這是json對象。

你可以通過數組獲得Json數組並獲取Json對象。

JSONArray contacts = new JSONArray(jsonStr); 

而不是使用

JSONObject jsonObj = new JSONObject(jsonStr); 

現在你可以獲取數據

 for (int i = 0; i < contacts.length(); i++) { 
     JSONObject c = contacts.getJSONObject(i); 

     //Get all required data using c. 

      String id = c.getString("id"); 
      String name = c.getString("start"); 

     } 
+0

我不明白對不起.... – Markus

+0

你有[{},{}]格式[]顯示JsonArray和{}這是json對象 –

+0

你可以使用由android提供的日誌來檢查數據。 –

相關問題