Json对象无法转换为jsonarray

时间:2014-10-09 12:03:20

标签: android json android-volley

在我的代码中,我需要使用JSON在文本视图中显示普通文本。我正在使用volley库来解析JSON。我的代码是

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);
}
}

当我点击按钮获取结果时,它只显示&#34; org.json.JSON.EXCEPTION。和值:-------- Json对象无法转换为jsonarray&#34;

我不知道自己犯了什么错误。我只是在吐司中得到这些错误。 请告诉我。

3 个答案:

答案 0 :(得分:0)

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

您正在对代码中所述的网址发出请求,如果我将其粘贴到浏览器中:

响应:

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

这是JSONObject,而不是JSONArray。因此,您可以将代码中的JSONArray设为JSONObject,然后提取您可能需要的JSONArrayjsonObject.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只有一个构造函数,你在super调用中看到5个参数(还有一个有4个参数,但仍然超过jsonarrayrequest中的3个)

所以我们必须改变一下

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);
}

答案 1 :(得分: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);
}

答案 2 :(得分: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);

        }