2017-02-17 61 views
-1

我曾嘗試解析JSON值到我的列表視圖。我得到的logcat錯誤爲json解析錯誤,而不是出現在listview中的結果,整個json響應出現在吐司,請幫我解決它。謝謝。在Android集成API的API集成JSON解析

這裏是我的Java代碼

MainActivity.java

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 = " https://private-2a004-androidtest3.apiary-mock.com/employeesList"; 

ArrayList<HashMap<String, String>> employeeList; 

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

    employeeList = new ArrayList<>(); 

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

    new Getemployees().execute(); 
} 

/** 
* Async task class to get json by making HTTP call 
*/ 
private class Getemployees 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); 

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

       // looping through All Contacts 
       for (int i = 0; i < employees.length(); i++) { 
        JSONObject c = employees.getJSONObject(i); 
        String firstName = c.getString("firstName"); 
        String lastName = c.getString("lastName"); 
        String designation = c.getString("designation"); 
        String city = c.getString("city"); 
        HashMap<String, String> emp = new HashMap<>(); 
        emp.put("firstName", firstName); 
        emp.put("lastName", lastName); 
        emp.put("designation",designation); 
        emp.put("city",city); 
        employeeList.add(emp); 
       } 
      } 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, employeeList, 
       R.layout.list_item, new String[]{"firstName","lastName","designation", "city"},new int[]{R.id.firstName, 
       R.id.lastName,R.id.city,R.id.designation}); 
     lv.setAdapter(adapter); 
    } 

} 

}

HttpHandler.java

public class HttpHandler { 
private static final String TAG = HttpHandler.class.getSimpleName(); 

    public HttpHandler() { 
    } 

    public String makeServiceCall(String reqUrl) { 
     String response = null; 
     try { 
      URL url = new URL(reqUrl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      // read the response 
      InputStream in = new BufferedInputStream(conn.getInputStream()); 
      response = convertStreamToString(in); 
     } catch (MalformedURLException e) { 
      Log.e(TAG, "MalformedURLException: " + e.getMessage()); 
     } catch (ProtocolException e) { 
      Log.e(TAG, "ProtocolException: " + e.getMessage()); 
     } catch (IOException e) { 
      Log.e(TAG, "IOException: " + e.getMessage()); 
     } catch (Exception e) { 
      Log.e(TAG, "Exception: " + e.getMessage()); 
     } 
     return response; 
    } 

    private String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line).append('\n'); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
} 

我的logcat:

02-17 15:45:03.667 24027-24149/com.example.simple E/MainActivity: Response from url: [ 
                     { 

                      "employee": 
                      [ 
                      { 
                       "id": "1", 
                       "firstName": "Ram", 
                       "lastName": "Kumar", 
                       "address" : "1/20, Rich street", 
                       "city" : "Karur", 
                       "zipcode" : "636138", 
                       "gender" : "male", 
                       "dob" : "20-May-1995", 
                       "designation":"developer", 
                       "mobile" : "9988776655", 
                       "email" : "[email protected]", 
                       "nationality" : "Indian", 
                       "language" : "English", 
                       "imageURL" : "https://dummyimage.com/500x500/d12ad1/fff.png&text=Ram", 
                       "skills": [ 
                       { 
                        "technical" : [ "C", "C++", "Java" ], 
                        "extra_curricular" : ["chess", "cricket"] 
                       }] 
                      }, 
                      { 
                       "id": "2", 
                       "firstName": "Kumari", 
                       "lastName": "Raja", 
                       "address" : "2/20, Rich street", 
                       "city" : "Coimbatore", 
                       "zipcode" : "636148", 
                       "gender" : "female", 
                       "dob" : "10-Jun-1995", 
                       "designation":"Tester", 
                       "mobile" : "8899667744", 
                       "email" : "[email protected]", 
                       "nationality" : "Indian", 
                       "language" : "Tamil", 
                       "imageURL" : "https://dummyimage.com/500x500/52d929/fff.png&text=Kumari", 
                       "skills": [ 
                       { 
                        "technical" : [ "C", "C++", ".net" ], 
                        "extra_curricular" : ["Tennis", "Carrom"] 
                       }] 
                      }, 
                      { 
                       "id": "3", 
                       "firstName": "Raja", 
                       "lastName": "Ravi", 
                       "address" : "13/20, Rich street", 
                       "city" : "Salem", 
                       "zipcode" : "636138", 
                       "gender" : "male", 
                       "dob" : "22-Jan-1994", 
                       "designation":"Team Lead", 
                       "mobile" : "", 
                       "email" : "[email protected]", 
                       "nationality" : "Indian", 
                       "language" : "English", 
                       "imageURL" : "https://dummyimage.com/500x500/bef0af/fff.png&text=Raja", 
                       "skills": [ 
                       { 
                        "technical" : [ "C", "C++", "Java" , "Android"], 
                        "extra_curricular" : ["chess", "cricket"] 
                       }] 
                      }, 
                      { 
                       "id": "4", 
                       "firstName": "Sheela", 
                       "lastName": "Ravi", 
                       "address" : "14/20, Rich street", 
                       "city" : "Madurai", 
                       "zipcode" : "636200", 
                       "gender" : "female", 
                       "dob" : "10-Feb-1985", 
                       "designation":"developer", 
                       "mobile" : "5566778899", 
                       "email" : "[email protected]", 
                       "nationality" : "Indian", 
                       "language" : "Tamil", 
                       "imageURL" : "https://dummyimage.com/500x500/e6866e/fff.png&text=Sheela", 
                       "skills": [ 
                       { 
                        "technical" : [ "photoshop", "Ruby" ], 
                        "extra_curricular" : ["Carrom", "Reading books"] 
                       }] 
                      }, 
                      { 
                       "id": "5", 
                       "firstName": "Shankar", 
                       "lastName": "Kumar", 
                       "address" : "15/20, Rich street", 
                       "city" : "Madurai", 
                       "zipcode" : "636300", 
                       "gender" : "Male", 
                       "dob" : "10-Feb-1985", 
                       "designation":"Sr.Developer", 
                       "mobile" : "5566778899", 
                       "email" : "sh[email protected]", 
                       "nationality" : "Indian", 
                       "language" : "Tamil", 
                       "imageURL" : "https://dummyimage.com/500x500/8f3532/fff.png&text=Shankar", 
                       "skills": [ 
                       { 
                        "technical" : [ "C", "C++" ], 
                        "extra_curricular" : ["chess", "Drawing"] 
                       }] 
                      }, 
                      { 
                       "id": "6", 
                       "firstName": "Suren", 
                       "lastName": "Saker", 
                       "address" : "16/20, Rich street", 
                       "city" : "Salem", 
                       "zipcode" : "636400", 
                       "gender" : "Male", 
                       "dob" : "14-Jan-1985", 
                       "designat 
02-17 15:45:03.676 24027-24149/com.example.simple E/MainActivity: Json parsing error: Value [{"employee":[{"id":"1","firstName":"Ram","lastName":"Kumar","address":"1\/20, Rich street","city":"Karur","zipcode":"636138","gender":"male","dob":"20-May-1995","designation":"developer","mobile":"9988776655","email":"[email protected]","nationality":"Indian","language":"English","imageURL":"https:\/\/dummyimage.com\/500x500\/d12ad1\/fff.png&text=Ram","skills":[{"technical":["C","C++","Java"],"extra_curricular":["chess","cricket"]}]},{"id":"2","firstName":"Kumari","lastName":"Raja","address":"2\/20, Rich street","city":"Coimbatore","zipcode":"636148","gender":"female","dob":"10-Jun-1995","designation":"Tester","mobile":"8899667744","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/dummyimage.com\/500x500\/52d929\/fff.png&text=Kumari","skills":[{"technical":["C","C++",".net"],"extra_curricular":["Tennis","Carrom"]}]},{"id":"3","firstName":"Raja","lastName":"Ravi","address":"13\/20, Rich street","city":"Salem","zipcode":"636138","gender":"male","dob":"22-Jan-1994","designation":"Team Lead","mobile":"","email":"[email protected]","nationality":"Indian","language":"English","imageURL":"https:\/\/dummyimage.com\/500x500\/bef0af\/fff.png&text=Raja","skills":[{"technical":["C","C++","Java","Android"],"extra_curricular":["chess","cricket"]}]},{"id":"4","firstName":"Sheela","lastName":"Ravi","address":"14\/20, Rich street","city":"Madurai","zipcode":"636200","gender":"female","dob":"10-Feb-1985","designation":"developer","mobile":"5566778899","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/dummyimage.com\/500x500\/e6866e\/fff.png&text=Sheela","skills":[{"technical":["photoshop","Ruby"],"extra_curricular":["Carrom","Reading books"]}]},{"id":"5","firstName":"Shankar","lastName":"Kumar","address":"15\/20, Rich street","city":"Madurai","zipcode":"636300","gender":"Male","dob":"10-Feb-1985","designation":"Sr.Developer","mobile":"5566778899","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/dummyimage.com\/500x500\/8f3532\/fff.png&text=Shankar","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"6","firstName":"Suren","lastName":"Saker","address":"16\/20, Rich street","city":"Salem","zipcode":"636400","gender":"Male","dob":"14-Jan-1985","designation":"Sr.Developer","mobile":"8899776655","email":"[email protected]","nationality":"Indian","language":"English","imageURL":"http:\/\/indianapublicmedia.org\/arts\/files\/2012\/04\/sample-gates-9-940x626.jpg","skills":[{"technical":["Java","Android"],"extra_curricular":["Reading","Stamp collection"]}]},{"id":"7","firstName":"Rajesh","lastName":"Kumar","address":"17\/20, Rich street","city":"Karur","zipcode":"636800","gender":"Male","dob":"10-Feb-1985","designation":"Sr.Developer","mobile":"5566778899","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"http:\/\/images.fonearena.com\/blog\/wp-content\/uploads\/2013\/11\/Lenovo-p780-camera-sample-10.jpg","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"8","firstName":"Sham","lastName":"Kumar","address":"18\/20, Rich street","city":"Salem","zipcode":"636700","gender":"Male","dob":"08-Feb-1985","designation":"Sr.Developer","mobile":"7788996655","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/taylorstaste.files.wordpress.com\/2014\/07\/screenshot-2014-07-03-10-25-41.png","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"9","firstName":"Jayakumar","lastName":"Ravi","address":"19\/20, Rich street","city":"Coimbatore","zipcode":"623300","gender":"Male","dob":"3-Mar-1986","designation":"Designer","mobile":"8879797979","email":"[email protected]","nationality":"Indian","language":"Tamil","imageURL":"http:\/\/images.fonearena.com\/blog\/wp-content\/uploads\/2013\/11\/google-nexus-5-macro-samples-1.jpg","skills":[{"technical":["Photoshop","Design tools"],"extra_curricular":["chess","Drawing"]}]},{ 
+0

我希望你'contact'關鍵是正確的,而你並不意味着'employee'因爲我們不能看到它在日誌中。如果它是正確的:嘗試'substring' e.getMessage()'從你的錯誤中移除前1000個(或5000或10000)字符,這樣你就可以看到錯誤的位置。否則,我建議您在計算機上運行此請求,並檢查JSON實際上是否來自某個在線服務的有效性。 – zed

+0

檢查您的JSONObject「{」和JSONArray「[」序列中的代碼與您的JSON比較,並且JSON中沒有「聯繫人」JSONArray employees = jsonObj.getJSONArray(「contacts」); –

+0

請發佈您的完整JSON響應,以便我可以幫到你 –

回答

1

試試這個,

 try { 


      JSONArray jsonArray=new JSONArray(jsonStr); 

      JSONObject jsonObj =jsonArray.getJSONObject(0); 

      // Getting JSON Array node 
      JSONArray employees = jsonObj.getJSONArray("employee"); 

      // looping through All Contacts 
      for (int i = 0; i < employees.length(); i++) { 
       JSONObject c = employees.getJSONObject(i); 
       String firstName = c.getString("firstName"); 
       String lastName = c.getString("lastName"); 
       String designation = c.getString("designation"); 
       String city = c.getString("city"); 
       HashMap<String, String> emp = new HashMap<>(); 
       emp.put("firstName", firstName); 
       emp.put("lastName", lastName); 
       emp.put("designation",designation); 
       emp.put("city",city); 
       employeeList.add(emp); 
      } 
     } catch (final JSONException e) { 

     } 
+0

@ Da1我覺得這個對你有用 –

+0

@ user2025187非常感謝,真的幫了我 – Da1

+0

@ZakiPathan,是Zaki,這對我很有用,非常感謝你 – Da1

0

Json的密鑰不匹配:

JSONArray jsonArray=new JSONArray(jsonStr); // As your response is in json array format 
JSONObject jsonObject =jsonArray.getJSONObject(0); 
// Getting JSON Array node 
JSONArray employees = jsonObject.getJSONArray("employee"); 

替換爲「員工」,將解決你的問題「接觸」鍵。

+0

好的......讓我檢查一下....找到你。 – Da1

+0

@ Da1結賬我的更新回答,應該可以工作 – Piyush

+0

讓我檢查一下吧.. – Da1

0

使用JSONArray jsArray = new JSONArray(jsonStr)instesd JSONObject jsonObj = new JSONObject(jsonStr)因爲您的響應是JsonArray。