2016-09-22 80 views
1

我一直在接收JSON對象作爲來自HttpsURLConnection的響應。我一直在用這個來解析迴應。Java HttpsURLConnection響應JSON數組

ObjectMapper map = new ObjectMapper(); 
JsonNode node = map.readTree(conn.getInputStream()); 

這對我來說工作正常,但現在我正在接收數組。我如何解析它們?

這是響應的一個例子,我得到:

"value": [1 ] 0: { "ID": "2135125324" "name": "John" "2ndName": null "lastName": "James" }

+0

能否請您顯示你從服務器收到的輸出 –

+0

@JithinKuriakose編輯了文章 –

+0

我認爲你的查詢已經在這個鏈接上得到了答案: [如何解析JSON數組(N ot Json對象)在Android](http://stackoverflow.com/questions/18977144/how-to-parse-json-array-not-json-object-in-android) – Mohit

回答

1

如果你正在使用的AsyncTask 請試試這個寫如下的代碼,它會幫助你

private void yourfunction() 
{ 

    class YourClass extends AsyncTask<String, Void, String> 
    { 


     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 

      try { 
       JSONObject jsonObj = new JSONObject(s); 
       user = jsonObj.getJSONArray("value"); 
       JSONObject c = user.getJSONObject(0); 
       String profile = c.getString("ID"); 
       String name = c.getString("name"); 



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


     } 

     @Override 
     protected String doInBackground(String... params) { 
      String s = params[0]; 
      BufferedReader bufferedReader = null; 
      try { 
       URL url = new URL("your url string"); 
       HttpURLConnection con= (HttpURLConnection) url.openConnection(); 
       bufferedReader=new BufferedReader(new InputStreamReader(con.getInputStream())); 
       String result; 
       result = bufferedReader.readLine(); 
       return result; 
      } 
      catch (Exception e) { 
       return null; 
      } 
     } 
    } 
    YourClass lu=new YourClass(); 
    lu.execute(); 
}