在使用参数发送JSON对象时获取JSON解析错误

时间:2013-12-13 08:53:01

标签: android json web-services parsing

解析数据时遇到以下问题。

"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" 

我想发送一个像这样的Request对象,并且想要在发送时打印请求对象: -

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

任何人都可以给我正确的解决方案来发送上述请求并得到回复。谢谢提前

3 个答案:

答案 0 :(得分:2)

这是实际的json格式

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

检查你的json格式

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

现在,您的服务器只会收到一个名为&#34; objTimesheet&#34; 的参数,其内容将是带有json数据的String。如果您的服务器脚本是PHP,则可以像这样获取JSON对象:

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

$ json_decoded是一个包含数据的数组。即,你可以使用$ json_decoded [&#34; Name&#34;]。

现在让我们回复一下。如果您希望客户收到JSONObject,您需要发送包含JSONObject有效字符串,否则您将获得现在获得的JSONException。< / p>

字符串:&#34; InsertTimesheetItemResult =已成功插入&#34; 不是有效的JSON字符串

应该是这样的:&#34; {&#34; InsertTimesheetItemResult&#34; :&#34;已成功插入&#34;}&#34;。

PHP具有函数 json_encode 来将对象编码为JSON字符串。要返回一个像我上面写的那样的String,你应该这样做:

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

我希望这会对你有所帮助。

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