Json数组无法转换为json对象

时间:2015-02-12 14:05:26

标签: android arrays json

我正在尝试向服务器发送请求并从服务器获取响应,但是当我运行我的应用程序时它崩溃并显示json数组无法转换为json对象..以下是我的代码和Web服务..

回应:

[
  {
        "id":"15","name":"",
         "contact":"",
          "email":"",
           "comp_name":"Tailor",
            "upload_dir":""
   },
    {
        "id":"16","name":"",
         "contact":"",
          "email":"",
           "comp_name":"Trailor",
            "upload_dir":""
   },
]

MainActivity.java

    JSONParser jsonParser = new JSONParser();
     JSONObject json;

       JSONArray searchresult=null;

 class searchs extends AsyncTask<String, String, String> {

        boolean failure = false;
        JSONObject jobj;
        String resultname;
         String match_Detail_id;
         String Names;
         String Ages;
         String Locations;
         String Images;
         String Casts;
         String Profiles;
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Processing..");
            pDialog.setIndeterminate(true);
           // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @SuppressWarnings("unused")
        @Override
        protected String doInBackground(String...args) {
            //Check for success tag
            //int success;
            Looper.prepare();

            String language=splang.getText().toString();
            String religion = sprelg.getText().toString();
            String marriage=spmrgstatus.getText().toString();
            String contri=spcountry.getText().toString();
            String states=spstate.getText().toString();
            String city=spcity.getText().toString();

            System.out.println("Lang : " + language);
            System.out.println("REligions : " + religion);
            System.out.println("Maritals : " + marriage);
            System.out.println("Countrys : " + contri);
            System.out.println("States : " + states);
            System.out.println("Citys : " + city);

             try {
                 //Building Parameters

                 List<NameValuePair> params = new ArrayList<NameValuePair>();

                 params.add(new BasicNameValuePair("cat_id", language));
                 params.add(new BasicNameValuePair("subcat_id", religion));
                 params.add(new BasicNameValuePair("product", marriage));
                 params.add(new BasicNameValuePair("state", contri));
                 params.add(new BasicNameValuePair("city", states));


                 Log.d("request!", "starting");
                 // getting product details by making HTTP request
                json = jsonParser.makeHttpRequest (
                     SEARCH_URL, "POST", params);

                 //check your log for json response
                 Log.d("Request attempt", json.toString());


                 //final String str = json.toString();

                // jobj = new JSONObject(json.toString());
                // final String msg = jobj.getString("searchresult");

                 searchresult = new JSONArray(json.toString());
                 for (int i = 0; i <searchresult.length(); i++) {
                     JSONObject c = searchresult.getJSONObject(i);

                     match_Detail_id = c.getString("id");
                     Log.d("Request attempt", match_Detail_id);
                     Names = c.getString("name");
                     Log.d("Request name", Names);
                     Profiles = c.getString("contact");
                     Log.d("Request profile", Profiles);
                     Images = c.getString("upload_dir");
                     Log.d("Request image", Images);
                     Casts = c.getString("email");
                     Log.d("Request cast", Casts);
                     Ages = c.getString("comp_name");
                     Log.d("Request age", Ages);



                     HashMap<String, String> hmp = new HashMap<String, String>();
                     hmp.put(TAG_AGE, Ages+" years");
                     hmp.put(TAG_CAST, Casts);
                     hmp.put(TAG_IMAGE, Images);

                     hmp.put(TAG_MATCH_ID, match_Detail_id);
                     hmp.put(TAG_NAME, Names);
                     hmp.put(TAG_PROFILE, Profiles);

                     alhmp.add(hmp);


                     //String age_fromc = c.getString("age_from");
                 }

                /* runOnUiThread(new  Runnable() 
                 {
                    @Override
                    public void run() 
                    {

                        Intent intent=new Intent(MainActivity.this,SearchResults.class);
                        intent.putExtra("match_data", alhmp);
                        //intent.putExtra("id", strtext);
                        intent.putExtra("prmatch_id", match_Detail_id);
                        startActivity(intent);

                    } 
                });*/


                 }catch (JSONException e) {
                 e.printStackTrace();
             }
             return null;
        }
        // After completing background task Dismiss the progress dialog
        protected void onPostExecute(String file_url) {
            //dismiss the dialog once product deleted
             pDialog.dismiss();


             alhmp.clear();


                splang.setText("Select");
                sprelg.setText("Select");

                spmrgstatus.setText("Select");
                spcountry.setText("Select Country");
                spstate.setText("Select State");
                spcity.setText("Select City");
                /*if(searchresult == null || searchresult.length() == 0){


                    Intent inss=new Intent(MainActivity.this,SearchResults.class);
                    inss.putExtra("match_data", alhmp);
                    //inss.putExtra("id", strtext);
                    inss.putExtra("prmatch_id", match_Detail_id);
                    startActivity(inss);

                }*/

    }}      

JSONParser

   public class JSONParser {

 static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";
  static JSONArray jsonarry=null;
  // constructor
  public JSONParser() {
  }

  // function get json from url
    // by making HTTP POST or GET method
  public JSONObject makeHttpRequest(String url, String method,
          List<NameValuePair> params) {

      // Making HTTP request
      try {
        // check for request method
          if(method.equals("POST")){
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);
              httpPost.setEntity(new UrlEncodedFormEntity(params));

              HttpResponse httpResponse = httpClient.execute(httpPost);
              HttpEntity httpEntity = httpResponse.getEntity();
             is = httpEntity.getContent();
          } else if(method.equals("GET")) {
              //request method is GET
              DefaultHttpClient httpClient = new DefaultHttpClient();
              String paramString = URLEncodedUtils.format(params, "utf-8");
              url += "?" + paramString;
              HttpGet httpGet = new HttpGet(url);

              HttpResponse httpResponse = httpClient.execute(httpGet);
              HttpEntity httpEntity = httpResponse.getEntity();
              is = httpEntity.getContent();
          }
      }catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }catch (ClientProtocolException e) {
          e.printStackTrace ();
      }catch (IOException e) {
          e.printStackTrace();
      }

      try {
          BufferedReader reader = new BufferedReader(new InputStreamReader(
          is, "iso-8859-1"),8);
          StringBuilder sb = new StringBuilder();
          String line = null;
          while ((line = reader.readLine()) != null) {
          sb.append(line + "\n");
          }
          is.close();
          json = sb.toString();
          Log.d("Request attempt","JSON >>>" +  json.toString());
          } catch (Exception e) {
          Log.e("Buffer Error", "Error converting result" + e.toString());
          }
    // try parse the string to a JSON object
      try { jObj = new JSONObject(json);
      } catch (JSONException e) {
          Log.e("JSON PArser", "Error Parsing data" + e.toString());
      }
      return jObj;
  }

3 个答案:

答案 0 :(得分:1)

jObj中的jObj = new JSONObject(json);更改为JSONArray。

你使用的jsonparser类总是以JSONObject的形式获得响应,你必须检查响应是JSONObject还是JSONArray然后转换它并将它返回给你的主类..

修改

你的答案JSONArray你知道吗?检查您的JSONParser类,您将获得响应json = sb.toString();。然后你将它转换为JSONObject,如jObj = new JSONObject(json);,所以它将显示错误。您必须将其设为JSONArray jArray = new JSONArray(json);,因为您的回复是JSONArray。

答案 1 :(得分:1)

修复你的Json字符串:

{ "record": [
     {
        "id":"15","name":"",
         "contact":"",
          "email":"",
           "comp_name":"Tailor",
            "upload_dir":""
     },
     {
        "id":"16","name":"",
         "contact":"",
          "email":"",
           "comp_name":"Trailor",
            "upload_dir":""
    }
  ]
}

使用this site检查您的结构。

答案 2 :(得分:1)

您可以尝试更改此行:

searchresult = new JSONArray(json.toString());

到这一行:

searchresult = json.getJSONArray(0);

但是你应该总是为JSON字符串添加一个键(如Trinimon建议的那样)并使用:

searchresult = json.getJSONArray(KEY_VALUE); // in Tinimon's example "record"

拥有你的JSON数组。