1

I want to create json object from a string that comes as a response from a servlet in my server.

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

    public JSONObject getJSONFromUrl(String url,String a) {

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("branchname", a));

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));

            HttpResponse httpResponse = httpClient.execute(httppost);
            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", "Error parsing data " + e.toString());
        }


        return jObj;            
}}

This is my servlet..

public class AvailabilityResponse extends HttpServlet {

@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    PrintWriter out=response.getWriter();

        String br_id;
        br_id=request.getParameter("branchname");

    try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888  /atmlivedetails","root","root");  
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("select atmbrno, atmbrname  from location_stat where act_brname='"+br_id+"'");
        int i=0;
        JSONArray jArray = new JSONArray();
        while(rs.next()){

    String s = rs.getString("atmbrno");
    String t = rs.getString("atmbrname");

    JSONObject arrayObj = new JSONObject();

    arrayObj.put("atmbrno",s);
    arrayObj.put("atmbrname",t);

    jArray.add(i,arrayObj);
    i++;
    }
    rs.close ();
    st.close ();
    out.print(jArray);
}

    catch(Exception e){
            out.print(e);
    }


}}

but when I run this it says Error

"parsing data org.json.JSONException: Value [{"atmbrname":"ANURADAPURA
[ATM 2]","atmbrno":"ATM084"},{"atmbrname":"MANNAR BRANCH  
","atmbrno":"ATM344"}] of type org.json.JSONArray cannot be converted
to JSONObject"

what is the wrong in this case?

Here is my calling class

public class ListAtmActivity extends ListActivity{

private static String url ="http://10.0.2.2:8080/hello/AvailabilityResponse";

//TextView error;
//String brName;

//Bundle b = getIntent().getExtras();
//String brName = b.getString("key");

private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String ATM_NO = "atmbrno";
private static final String ATM_PLACE = "atmbrname";

// contacts JSONArray
//JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item);

    String brName=getIntent().getExtras().getString("key");


    /*Bundle b = getIntent().getExtras();
    brName = b.getString("key");
    */


    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url,brName);


    try{
        //String results;
        JSONArray contacts = json.getJSONArray(TAG_CONTACTS);

        for(int i = 0; i < contacts.length(); i++){
            JSONObject json_data = contacts.getJSONObject(i);

            // Storing each json item in variable
            String atm_id = json_data.getString(ATM_NO);
            String atm_name = json_data.getString(ATM_PLACE);

            HashMap<String, String> map = new HashMap<String, String>();

            map.put(ATM_NO, atm_id);
            map.put(ATM_PLACE, atm_name);

            contactList.add(map);                
        }                       
    }

    catch(JSONException e) {
        e.printStackTrace();

    }

    /**
     * Updating parsed JSON data into ListView
     * */
   ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_main,
            new String[] { ATM_NO, ATM_PLACE }, new int[] {
                    R.id.name , R.id.email });

    setListAdapter(adapter);

}}
16
  • because you are sending a json array just change the json object lines to json array all operations are allowed or else aadan{ in front and} in end of the retrieved string it will doo Commented Sep 13, 2012 at 5:56
  • I think the problem comes with return array from servlet..it may not according to correct format..but i can't get what's the wrong? Commented Sep 13, 2012 at 5:59
  • @droidhot- can u correct that wrong..i can't get it.. Commented Sep 13, 2012 at 6:02
  • there is no problem at all the return is an array not an object either use an jsonarray instead of json object or add opening and closing braces to the array so it becomes an object refer w3schools for further details on json Commented Sep 13, 2012 at 6:04
  • [{"atmbrname":"ANURADAPURA [ATM 2]","atmbrno":"ATM084"},{"atmbrname":"MANNAR BRANCH ","atmbrno":"ATM344"}] this is an array to make it an object { [{"atmbrname":"ANURADAPURA [ATM 2]","atmbrno":"ATM084"},{"atmbrname":"MANNAR BRANCH ","atmbrno":"ATM344"}]} change to this Commented Sep 13, 2012 at 6:05

3 Answers 3

1

you can change json object to json array,

  public class JSONParser {

static InputStream is = null;
static JSONArray jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

    public JSONArray getJSONFromUrl(String url,String a) {

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("branchname", a));

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));

            HttpResponse httpResponse = httpClient.execute(httppost);
            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 Array
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }


        return jObj;            
}}

Your return data is json array, but you convert json object ,that's only Exception raise.

  static JSONArray jObj = null;

   // try parse the string to a JSON Array
    try {
        jObj = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
Sign up to request clarification or add additional context in comments.

Comments

1

as per your request posting

   public class JSONParser {

    static InputStream is = null;
     static JSONArray jObj = null;
    static String json = "";

     // constructor
    public JSONParser() {

  }

public JSONArray getJSONFromUrl(String url,String a) {

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("branchname", a));

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(postParameters));

        HttpResponse httpResponse = httpClient.execute(httppost);
        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 JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }


    return jObj;            
   }}

and in the parsing class

 public class ListAtmActivity extends ListActivity{

 private static String url ="http://10.0.2.2:8080/hello/AvailabilityResponse";

 //TextView error;
  //String brName;

   //Bundle b = getIntent().getExtras();
 //String brName = b.getString("key");

private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String ATM_NO = "atmbrno";
 static final String ATM_PLACE = "atmbrname";

 // contacts JSONArray
  //JSONArray contacts = null;

    @Override
  public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);

String brName=getIntent().getExtras().getString("key");


/*Bundle b = getIntent().getExtras();
brName = b.getString("key");
*/


// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

// Creating JSON Parser instance
JSONParser jParser = new JSONParser();

// getting JSON string from URL
 JSONArray contacts = jParser.getJSONFromUrl(url,brName);


try{
    //String results;


    for(int i = 0; i < contacts.length(); i++){
        JSONObject json_data = contacts.getJSONObject(i);

        // Storing each json item in variable
        String atm_id = json_data.getString(ATM_NO);
        String atm_name = json_data.getString(ATM_PLACE);

        HashMap<String, String> map = new HashMap<String, String>();

        map.put(ATM_NO, atm_id);
        map.put(ATM_PLACE, atm_name);

        contactList.add(map);                
    }                       
}

catch(JSONException e) {
    e.printStackTrace();

}

  /**
   * Updating parsed JSON data into ListView
   * */
  ListAdapter adapter = new SimpleAdapter(this, contactList,
        R.layout.list_main,
        new String[] { ATM_NO, ATM_PLACE }, new int[] {
                R.id.name , R.id.email });

   setListAdapter(adapter);

   }}

1 Comment

It works...Thank You very much..No errors but still that Listview not happens..I have to work with that..!
0

you need JsonArray to parse the getting String , basically you get JsonArray in your Response.

JSONArray jObj = null;

   // try parse the string to a JSON Array
    try {
        jObj = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

Comments

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.