2014-10-09 145 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); 

     }