Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I searched for many solution but stil don't work. I still getting the error of converting string to JSONObject Here is my code:

 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));
            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", json);
            //Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

This is the string that i wanted to parse:

{"products":[{"pid":"1","name":"abc","price":"222.00","created_at":"2013-04-02 12:44:26","updated_at":"0000-00-00 00:00:00"}],"success":1}

I learned this code from here.

Also the jObj = new JSONObject(json.substring(3)); dont work for me.

I SOLVED THE PROBLEM: The problem is on my string which i actually echo some comment in my php and it included in my json string. So i remove my echo from my php and everything wen smoothly. THANKS!

share|improve this question
    
use Log.e("JSON Response", "JSon String :- " + json); and check log you are getting valid json string from server from server in response –  ρяσѕρєя K Apr 2 '13 at 7:12
    
your json is not vaild. –  rajeshwaran Apr 2 '13 at 7:13
add comment

3 Answers

Make sure to validate your json. You can use http://jsonlint.com/

share|improve this answer
    
i have validated it and it's valid. –  max Apr 2 '13 at 8:10
add comment

Your JSON is invalid. You are missing one left bracket [ that indicates JSONArray It should be:

    {
        "products": [
          {
          "pid":"1",
          "name":"abc",
          "price":"222.00",
          "created_at":"2013-04-02 12:44:26",
          "updated_at":"0000-00-00 00:00:00"
          }
        ],
        "success":1
    }

Update:

Your problem is this:

if (method == "POST") { .. } // and same for GET

This always return false because you are trying to compare strings with == operator that compares references. You have to use equals() method because you want to compare values of strings.

share|improve this answer
    
I getting the same error even after i balanced the brackets. –  max Apr 2 '13 at 7:29
    
@max it's strange. Try to remove encoding from BufferedReader. –  Sajmon Apr 2 '13 at 7:40
    
removed and it's still the same. I edited my post above and posted my entire method maybe you could spot any problem there? I am still new to this –  max Apr 2 '13 at 7:53
    
@max check updated answer. –  Sajmon Apr 2 '13 at 8:25
    
i tried using method.equals.("GET") but still din't work. Thanks for the reply. –  max Apr 2 '13 at 9:40
add comment
package com.example.aam1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;

import org.json.JSONObject;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;

    static JSONArray jarr = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    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();

                if(httpEntity == null)
                {      String msg = "No response from server";   
                return null;
                }            
                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);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString().trim();
            Log.i("StringBuilder...", json);
        } 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.substring(3));
            jarr = new JSONArray(json);
        } catch (JSONException e) {
           // Log.e("JSON Parser", "Error parsing data " + e.toString());
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);

            try {
                jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
            } catch (Exception e0) {

                Log.e("JSON Parser0", "Error parsing data0 [" + e0.getMessage()+"] "+json);
                Log.e("JSON Parser0", "Error parsing data0 " + e0.toString());

                try {
                    jObj = new JSONObject(json.substring(1));
                } catch (Exception e1) {

                    Log.e("JSON Parser1", "Error parsing data1 [" + e1.getMessage()+"] "+json);
                    Log.e("JSON Parser1", "Error parsing data1 " + e1.toString());

                    try {
                        jObj = new JSONObject(json.substring(2));
                    } catch (Exception e2) {

                        Log.e("JSON Parser2", "Error parsing data2 [" + e2.getMessage()+"] "+json);
                        Log.e("JSON Parser2", "Error parsing data2 " + e2.toString());

                        try {
                            jObj = new JSONObject(json.substring(3));
                        } catch (Exception e3) {

                            Log.e("JSON Parser3", "Error parsing data3 [" + e3.getMessage()+"] "+json);
                            Log.e("JSON Parser3", "Error parsing data3 " + e3.toString());

                        }
                    }
                }
            }

        }

        // return JSON String
        return jObj;
 //       return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));

    }
} 
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.