2013-12-13 51 views
1

解析下面的數據遇到問題時。在使用參數發送JSON對象時在JSON解析中獲取錯誤

"12-13 14:18:41.769: E/JSON Parser(17409): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject" 

我想送一個像這樣的請求對象,也想打印請求對象同時發送: -

"objTimesheet" : 

{ 

"ClassicLevel" : "1", 
"CurrentLevel" : "2", 
"UpdatedDate" : "5-12-13", 
"Name":"Ankit", 
"UpdatedTime": "20", 
"Message":"" 

} 

這是我的JSON解析器類: -

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

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

     // Making HTTP request 
     try { 

      // check for request method 
      if (method == "POST") { 
       // request method is POST 
       // defaultHttpClient 
       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 == "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); 
     /* BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);*/ 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.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 JSON String 
     return jObj; 


    } 
} 

在我的活動中,我執行以下操作: -

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

     params1.add(new BasicNameValuePair(CLASSICLevel, "1")); 
     params1.add(new BasicNameValuePair(CURRENTLevel, "2")); 
     params1.add(new BasicNameValuePair(UPDATEDate, "345")); 
     params1.add(new BasicNameValuePair(NAME, "Nil")); 
     params1.add(new BasicNameValuePair(UPDATETIME, "10")); 

     json = jparser.makeHttpRequest(url_login, "POST", params1); 

任何一個可以給我妥善解決這一提前發出上述請求,並得到response..Thanks

+1

您可以登錄響應,並張貼 – Raghunandan

+0

這將是輸出ISF sucees:---- InsertTimesheetItemResult =成功插入 –

回答

2

這是實際的JSON格式

{"countrylist":[{"id":"241","country":" India"}]} 

檢查您的JSON格式

+0

但如何我把我的上述請求對象,打印它將發送。 –

0

的導致此錯誤的字符串是響應,而不是請求之一。此外,你的代碼你沒有發送JSONObject,你只是發送5個不同的參數。

讓我們從請求開始。您無法直接發送JSONObject到您的服務器,您需要將它作爲String發送,然後在服務器中解析它以獲取JSONObject。響應也是如此,您將收到一個要解析的字符串。

因此,讓我們創建您的客戶端JSONObject並將其添加到參數列表:

// Let's build the JSONObject we want to send 
JSONObject inner_content = new JSONObject(); 

inner_content 
    .put(CLASSICLevel, "1") 
    .put(CURRENTLevel, "2") 
    .put(UPDATEDate, "345") 
    .put(NAME, "Nil") 
    .put(UPDATETIME, "10"); 


JSONObject json_content= new JSONObject(); 
json_content.put("objTimesheet", inner_content); 

// TO PRINT THE DATA 
Log.d(TAG, json_content.toString()); 

// Now let's place it in the list of NameValuePair. 
// The parameter name is gonna be "json_data" 
List<NameValuePair> params1 = new ArrayList<NameValuePair>(); 
params1.add(new BasicNameValuePair("json_data", json_content.toString())); 

// Start the request function 
json = jparser.makeHttpRequest(url_login, "POST", params1); 

現在你的服務器將只接收一個參數叫做「objTimesheet」,其內容將是一個String與JSON數據。如果您的服務器腳本是PHP,就可以得到此JSON對象是這樣的:

$json = $_POST['json_data']; 
$json_replaced = str_replace('\"', '"', $json); 
$json_decoded = json_decode($json_replaced, true); 

$ json_decoded是包含數據的數組。也就是說,你可以使用$ json_decoded [「Name」]。

現在讓我們來回應一下。如果你希望你的客戶端收到JSONObject,你需要發送一個有效的字符串,包含JSONObject,否則你會得到你現在得到的JSONException

字符串:「InsertTimesheetItemResult =插入成功」不是有效的JSON字符串

它應該是這樣的:「{」InsertTimesheetItemResult「:」插入成功「}」。

PHP具有功能json_encode將對象編碼爲JSON字符串。要返回像我上面寫的字符串,你應該這樣做:

$return_data["InsertTimesheetItemResult"] = "Inserted successfully"; 
echo json_encode($return_data); 

我希望這可以幫助你。

+0

但objTimesheet是我想用makeHttpRequest發送的JSON對象。 –

+0

在我上面的代碼中,我發送了一個名爲「objTimesheet」的參數,其值爲:「{」ClassicLevel「:」1「,」CurrentLevel「:」2「,」UpdatedDate「:」345「,」Name「無「,」更新時間「:」無「}」。那不是你想要的? –

+0

字符串爲: - {「UpdatedTime」:「10」,「Name」:「Nil」,「CurrentLevel」:「2」,「Message」:「Hi」,「UpdatedDate」:「345」,「ClassicLevel」 「1」} –

0

嘗試這樣

private JSONArray mJArray = new JSONArray(); 
     private JSONObject mJobject = new JSONObject(); 
     private String jsonString = new String(); 

    mJobject.put("username", contactname.getText().toString()); 
        mJobject.put("phonenumber",phonenumber.getText().toString()); 
        mJArray.put(mJobject); 
        Log.v(Tag, "^============send request" + mJArray.toString()); 
        contactparams.add(new BasicNameValuePair("contactdetails", mJArray.toString())); 
        Log.v(Tag, "^============send request params" + mJArray.toString()); 
        jsonString=WebAPIRequest.postJsonData("http://localhost/contactupload/contactindex.php",contactparams); 
HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(url); 
// httppost.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
    try { 
      httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 


      /* String paramString = URLEncodedUtils.format(params, HTTP.UTF_8); 
      String sampleurl = url + "" + paramString; 
      Log.e("Request_Url", "" + sampleurl);*/ 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 
      if (response != null) { 
        InputStream in = response.getEntity().getContent(); 
        response_string = WebAPIRequest.convertStreamToString(in); 

      } 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 

    return response_string;