2013-12-13 42 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;