Born To Win
Born To Win

Reputation: 3329

Getting Error in JSON Parsing while sending an JSON object with parameter

While parsing the data faced problem below.

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

I want to send an Request object like this and also want to print the request object while sending:-

"objTimesheet" : 

{

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

}

This is my JSON parser class:-

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;


    }
}

And In my activity I execute this following:-

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

Can any one give me proper solution for this to send the above request and get the response..Thanks in advance

Upvotes: 1

Views: 3260

Answers (3)

PX Developer
PX Developer

Reputation: 8145

The string that's causing this error is the response, not the request one. Also, with your code you are not sending a JSONObject, you are just sending 5 different parameters.

Let's begin with the request. You cannot send a JSONObject directly to your server, you need to send it as a String and then parse it in the server to get the JSONObject back. The same goes with the response, you will receive a String to parse.

So let's create a JSONObject in your client and add it to the parameters list:

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

Now your server will receive just ONE parameter called "objTimesheet" whose content will be a String with the json data. If your server script is PHP, you can get the JSON Object back like this:

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

$json_decoded is an array containing your data. I.e., you can use $json_decoded["Name"].

Let's go to the response now. If you want your client to receive a JSONObject you need to send a valid string containing a JSONObject, otherwise you get the JSONException you are getting now.

The String: "InsertTimesheetItemResult=Inserted successfully" IS NOT a valid JSON string.

It should be something like: "{"InsertTimesheetItemResult" : "Inserted successfully"}".

PHP has the function json_encode to encode objects to JSON strings. To return a String like the one I wrote above, you should do something like this:

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

I hope this helps you.

Upvotes: 0

skyshine
skyshine

Reputation: 2864

try it like this

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;

Upvotes: 0

The Ray of Hope
The Ray of Hope

Reputation: 738

this is actual json format

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

check your json format

Upvotes: 2

Related Questions