1

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

2
  • 1
    can you log the response and post it Commented Dec 13, 2013 at 8:54
  • This will be the output isf sucees:----InsertTimesheetItemResult=Inserted successfully Commented Dec 13, 2013 at 9:07

3 Answers 3

2

this is actual json format

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

check your json format

Sign up to request clarification or add additional context in comments.

1 Comment

But how to i send my above request object and print it will sending.
0

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;

Comments

0

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.

8 Comments

But the objTimesheet is an JSON object i want to send this also with the makeHttpRequest.
In my code above I'm sending a parameter named "objTimesheet" whose value is: "{"ClassicLevel":"1", "CurrentLevel":"2", "UpdatedDate":"345", "Name":"Nil", "UpdatedTime": "Nil"}". That's not what you want?
String is:-{"UpdatedTime":"10","Name":"Nil","CurrentLevel":"2","Message":"Hi","UpdatedDate":"345","ClassicLevel":"1"}
And i want this:-{ "objTimesheet": {"UpdatedTime":"10","Name":"Nil","CurrentLevel":"2","Message":"Hi","UpdatedD‌​ate":"345","ClassicLevel":"1"}}
You can easily add JSONObjects inside of other JSONObjects. Check the code above, I just edited it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.