2014-10-09 148 views
1

在我的代碼中,我需要使用JSON在文本視圖中顯示普通文本。我正在使用排球庫來解析JSON。而我的代碼是Json對象無法轉換爲jsonarray

public class PrincipalSpeechFragment extends Fragment implements OnClickListener { 

public PrincipalSpeechFragment(){} 

private String urlJsonArry = "http://imaginetventures.net/sample/everwin_vidhyashram/webservice/rest/?module=speech&from=1-9-2014&to=30-9-2014"; 

private static String TAG = PrincipalSpeechFragment.class.getSimpleName(); 

// JSON Node names 
private static final String TAG_PRINCIPAL_SPEECH ="Principal Speech"; 
private static final String TAG_SPEECH= "speech"; 
private static final String TAG_DESC = "desc"; 

String tag_json_obj = "json_obj_req"; 

private Button getPrincipalSpeech; 

// Progress dialog 
//private ProgressDialog pDialog; 

private TextView txtResponse; 

// temporary string to show the parsed response 
private String jsonResponse; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.fragment_principal_speech, container, false); 

    return rootView; 
} 

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onActivityCreated(savedInstanceState); 

    getPrincipalSpeech = (Button) getActivity().findViewById(R.id.idForPrinciSpeech); 

    txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse); 

    getPrincipalSpeech.setOnClickListener(this); 
} 

@Override 
public void onClick(View arg0) { 
    // TODO Auto-generated method stub 
    makeJsonArrayRequest(); 
} 

private void makeJsonArrayRequest() { 

    JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, 
      new Response.Listener<JSONArray>() { 
     @Override 
     public void onResponse(JSONArray response) { 
      Log.d(TAG, response.toString()); 

      try { 
       // Parsing json array response 
       // loop through each json object 
       jsonResponse = ""; 
       for (int i = 0; i < response.length(); i++) { 

        JSONObject speechobj = (JSONObject) response 
          .get(i); 

        /*String speech = speechobj.getString("speech"); 
        String email = speech.getString("email"); 
        JSONObject phone = speech 
          .getJSONObject("speech"); 
        String home = phone.getString("home"); 
        String mobile = phone.getString("mobile");*/ 

        /*jsonResponse += "Speech: " + speech + "\n\n"; 
        /*jsonResponse += "Email: " + email + "\n\n";*/ 
        /*jsonResponse += "Home: " + home + "\n\n"; 
        jsonResponse += "Mobile: " + mobile + "\n\n\n";*/ 

       } 

       txtResponse.setText(jsonResponse); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
       Toast.makeText(getActivity().getApplicationContext(), 
         "Error: " + e.getMessage(), 
         Toast.LENGTH_LONG).show(); 
      } 

      //hidepDialog(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      VolleyLog.d(TAG, "Error: " + error.getMessage()); 
      Toast.makeText(getActivity().getApplicationContext(), 
        error.getMessage(), Toast.LENGTH_SHORT).show(); 
      //hidepDialog(); 
     } 
    }); 

    // Adding request to request queue 
    AppController.getInstance().addToRequestQueue(req); 
} 
} 

當我按一下按鈕,得到的結果它只是顯示「org.json.JSON.EXCEPTION和值:-------- JSON對象不能轉換到jsonarray「

我不知道我做了什麼錯誤。我只是在烤麪包片中發現這些錯誤。 請告訴我。

+0

什麼是Log.d的值(TAG,response.toString());? – kyogs 2014-10-09 12:08:28

+0

JSONObject可以嵌套其他JSONObjects和JSONArrays ...查找導致異常並將其轉換爲調用attr.getJSONArray(「attr」)的句子; – 2014-10-09 12:08:44

回答

0
private String urlJsonArry = "http://imaginetventures.net/sample/everwin_vidhyashram/webservice/rest/?module=speech&from=1-9-2014&to=30-9-2014"; 

你讓在代碼中規定的URL的請求,如果我把它粘貼到瀏覽器:

響應:

{ 
    "Principal Speech": [ 
     { 
      "speech": "Lorem (... et cetera)." 
     } 
    ] 
} 

這是一個JSONObject,不一個JSONArray。所以,你可以在你的代碼JSONObjectJSONArray,然後提取JSONArray你可能想:jsonObject.getJSONArray("Principal Speech");

編輯:添加代碼

private void makeJSONObjectRequest() { 

    JsonObjectRequest req = new JsonObjectRequest(urlJsonArry, //Dont know where that came from, but JsonArrayRequest as classname will probably still work. Custom/your own class, I guess. As long as the type JSONArray is changed to JSONObject 
      new Response.Listener<JSONObject>() { //JSONObject instead of JSONArray 
     @Override 
     public void onResponse(JSONObject response) {//JSONObject instead of JSONArray 
      JSONArray speechArray = response.getJSONArray("Principal Speech"); //get the array from the JSONObject 
      Log.d(TAG, response.toString()); 
      // The rest is the same 
      try { 
       // Parsing json array response 
       // loop through each json object 
       jsonResponse = ""; 
       for (int i = 0; i < response.length(); i++) { 

        JSONObject speechobj = (JSONObject) response 
          .get(i); 

        /*String speech = speechobj.getString("speech"); 
        String email = speech.getString("email"); 
        JSONObject phone = speech 
          .getJSONObject("speech"); 
        String home = phone.getString("home"); 
        String mobile = phone.getString("mobile");*/ 

        /*jsonResponse += "Speech: " + speech + "\n\n"; 
        /*jsonResponse += "Email: " + email + "\n\n";*/ 
        /*jsonResponse += "Home: " + home + "\n\n"; 
        jsonResponse += "Mobile: " + mobile + "\n\n\n";*/ 

       } 

       txtResponse.setText(jsonResponse); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
       Toast.makeText(getActivity().getApplicationContext(), 
         "Error: " + e.getMessage(), 
         Toast.LENGTH_LONG).show(); 
      } 

      //hidepDialog(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      VolleyLog.d(TAG, "Error: " + error.getMessage()); 
      Toast.makeText(getActivity().getApplicationContext(), 
        error.getMessage(), Toast.LENGTH_SHORT).show(); 
      //hidepDialog(); 
     } 
    }); 

    // Adding request to request queue 
    AppController.getInstance().addToRequestQueue(req); 
} 

EDIT2:重寫:

所以JsonArrayObjectRequest是與JsonObjectRequest有點不同

JSONArrayRequest

public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) { 
    super(Method.GET, url, null, listener, errorListener); 
} 

JsonObjectRequest只與5個PARAMS您在super調用看到(也Theres一個有4個參數,可以但仍比3從jsonarrayrequest更多)

一個構造函數,因此我們不得不改變了一下

private void makeJSONObjectRequest() { 
    Response.Listener<JSONObject> oklistener = new Response.Listener<JSONObject>() { 
     @Override 
     public void onResponse(JSONObject response) { 
      JSONArray speechArray = response.getJSONArray("Principal Speech"); 
      Log.d(TAG, response.toString()); 
      // The rest is the same 
      try { 
       // Parsing json array response 
       // loop through each json object 
       jsonResponse = ""; 
       for (int i = 0; i < speechArray.length(); i++) { 

        JSONObject speechobj = (JSONObject) speechArray.get(i); 

        /*String speech = speechobj.getString("speech"); 
        String email = speech.getString("email"); 
        JSONObject phone = speech 
          .getJSONObject("speech"); 
        String home = phone.getString("home"); 
        String mobile = phone.getString("mobile");*/ 

        /*jsonResponse += "Speech: " + speech + "\n\n"; 
        /*jsonResponse += "Email: " + email + "\n\n";*/ 
        /*jsonResponse += "Home: " + home + "\n\n"; 
        jsonResponse += "Mobile: " + mobile + "\n\n\n";*/ 

       } 

       txtResponse.setText(jsonResponse); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
       Toast.makeText(getActivity().getApplicationContext(), 
         "Error: " + e.getMessage(), 
         Toast.LENGTH_LONG).show(); 
      } 

      //hidepDialog(); 
     } 
    }; 
    Response.ErrorListener errorlistener = new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      VolleyLog.d(TAG, "Error: " + error.getMessage()); 
      Toast.makeText(getActivity().getApplicationContext(), 
        error.getMessage(), Toast.LENGTH_SHORT).show(); 
      //hidepDialog(); 
     } 
    }; 
    //Above instantiated the listeners, to make it a little more understandable. Here the second param => null. That sets the method to GET 
    JsonObjectRequest req = new JsonObjectRequest(urlJsonArry, null, oklistener, errorlistener); 

    // Adding request to request queue 
    AppController.getInstance().addToRequestQueue(req); 
} 
+0

我需要打印該語音內容,該怎麼做。你可以編輯我的代碼。 – IndependentDev 2014-10-09 12:16:54

+0

@SanjayAD查看編輯 – stealthjong 2014-10-09 12:27:30

+0

顯示錯誤兄弟,錯位的構造函數 – IndependentDev 2014-10-09 12:36:05

0

在你的迴應中,你得到了JSONObject,所以使用下面的代碼。

JSONObject jsnobject = new JSONObject(response); 

JSONArray jsonArray = jsnobject.getJSONArray("Principal Speech"); 
    for (int i = 0; i < jsonArray.length(); i++) { 
     JSONObject explrObject = jsonArray.getJSONObject(i); 
} 
+0

中的代碼,我需要替換此代碼。 – IndependentDev 2014-10-09 12:25:41

0
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() 
     { 
      @Override 
      public void onResponse(JSONArray response) { 
       // TODO Auto-generated method stub 

      } 
     }; 
     Response.ErrorListener errorListener = new Response.ErrorListener() 
     { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       // TODO Auto-generated method stub 

      } 
     }; 

並使用

JsonArrayRequest jr =new JsonArrayRequest(Request.Method.GET,url, listener, errorListener) ; 

編輯2:

我檢查源,它看起來像下面

public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) { 
      super(Method.GET, url, null, listener, errorListener); 

     }