2015-01-23 9 views
0

Я получаю ответ json на стороне сервера, чтобы загрузить мое меню, я дважды пробовал, и он дал это сообщение об ошибке (данные анализа ошибок org.json.JSONException).Получение частичного ответа от Json

Причина в том, что я получаю ответ частично, в обеих попытках я получил разные ответы, как показано на изображениях. я думаю, что я не получаю полный ответ json, получая только частичный ответ. что я должен сделать, чтобы получить полный ответ.

это мой код

@Override 
protected JSONObject doInBackground(String... params) { 

    String path = null; 
    String response = null; 
    HashMap<String, String> request = null; 
    JSONObject requestJson = null; 
    DefaultHttpClient httpClient = null; 
    HttpPost httpPost = null; 
    StringEntity requestString = null; 
    ResponseHandler<String> responseHandler = null; 

    // get the email and password 


    try { 
     path = "http://xxxxxxxxxxxxxxxxxxx"; 

     new URL(path); 
    } catch (MalformedURLException e) { 

     e.printStackTrace(); 
    } 

    try { 

     // set the API request 
     request = new HashMap<String, String>(); 
     request.put(new String("CetegoryCode"), "P"); 
     request.entrySet().iterator(); 

     // Store locations in JSON 
     requestJson = new JSONObject(request); 
     httpClient = new DefaultHttpClient(); 
     httpPost = new HttpPost(path); 
     requestString = new StringEntity(requestJson.toString()); 

     // sets the post request as the resulting string 
     httpPost.setEntity(requestString); 
     httpPost.setHeader("Content-type", "application/json"); 

     // Handles the response 
     responseHandler = new BasicResponseHandler(); 
     response = httpClient.execute(httpPost, responseHandler); 

     responseJson = new JSONObject(response); 

    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 
    try { 
     responseJson = new JSONObject(response); 

    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    return responseJson; 

} 

это изображение

enter image description here

+0

ответ, который у получает от вашего АФИ возвращающегося JSONObject или JsonArray? – user1140237

+0

JsonArray >> ответ начинается следующим образом: Value [{"ItemCode": "ABCD", "IsMayoBaseAvailable": false, –

+0

Вы получаете ответ в ответ Json = new JSONObject (response); ? – user1140237

ответ

0

Попробуйте ниже код для разбора и получить ответ в формате JSON:

public static JSONObject getJSONFromUrl(String url) { 
    // Making HTTP request 
    try { 
     URL url1 = new URL(url); 
     HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); 
     conn.setReadTimeout(10000 /* milliseconds */); 
     conn.setConnectTimeout(15000 /* milliseconds */); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     // Starts the query 
     conn.connect(); 
     InputStream stream = conn.getInputStream(); 
     json = convertStreamToString(stream); 

     stream.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    // 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 JSON String 
    return jObj; 

} 

static String convertStreamToString(java.io.InputStream is) { 
     java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); 
     return s.hasNext() ? s.next() : ""; 
    } 

Используйте getJSONFromUrl метод как ниже в вашем коде:

@Override 
protected JSONObject doInBackground(String... params) { 

    String path = null; 
    String response = null; 
    HashMap<String, String> request = null; 
    try { 
     responseJson = new JSONObject(response); 
     responseJson =getJSONFromUrl("http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p"); 

    }catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 
return responseJson; 
} 
0

Если ваш ответ возвращает JsonArray, вам нужно установить строку ответа jtonarray. создайте экземпляр jsonarray и заполните его ответом.

если его нормальная GET WS Thn вы можете добавить параметры в URL как строка запроса

protected Void doInBackground(String... urls) { 

      /************ Make Post Call To Web Server ***********/ 
      BufferedReader reader = null; 
      try { 
       // Append parameters with values eg ?CetegoryCode=p 
       String path = "http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p"; 
       URL url = new URL(path); 
       URLConnection conn = url.openConnection(); 
       conn.setDoOutput(true); 
       OutputStreamWriter wr = new OutputStreamWriter(
         conn.getOutputStream()); 
       wr.write(data); 
       wr.flush(); 

       // Get the server response 

       reader = new BufferedReader(new InputStreamReader(
         conn.getInputStream())); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        sb.append(line + ""); 
       } 

       Content = sb.toString(); 
       JSONArray jArray = new JSONArray(Content); 
       if (jArray != null) 
        Log.e("Data", "" + jArray.length()); 
      } catch (Exception ex) { 
       Error = ex.getMessage(); 
      } finally { 
       try { 

        reader.close(); 
       } 

       catch (Exception ex) { 
       } 
      } 

      /*****************************************************/ 
      return null; 
     }