2

hi hello I am new to android.I am getting response from server. But i get the following response..

getting the following error

Value {"Elec":"Cup1"} at 1 of type java.lang.String cannot be converted to JSONObject

The responce is as follows

{"Electronics":["{\"Elec\":\"Cup0\"}","{\"Elec\":\"Cup1\"}","{\"Elec\":\"Cup2\"}","{\"Elec\":\"Cup3\"}","{\"Elec\":\"Cup4\"}","{\"Elec\":\"Cup5\"}","{\"Elec\":\"Cup6\"}","{\"Elec\":\"Cup7\"}","{\"Elec\":\"Cup8\"}","{\"Elec\":\"Cup9\"}"],"Printable":["{\"Print\":\"Mug0\"}","{\"Print\":\"Mug1\"}","{\"Print\":\"Mug2\"}","{\"Print\":\"Mug3\"}","{\"Print\":\"Mug4\"}","{\"Print\":\"Mug5\"}","{\"Print\":\"Mug6\"}","{\"Print\":\"Mug7\"}","{\"Print\":\"Mug8\"}","{\"Print\":\"Mug9\"}"]}

And i send and receive the responce is as follows

    class SliderImages extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... urls) {

        return POST1(urls[0]);
    }

    @Override
    public void onPostExecute(String result) {

    }

}

public String POST1(String url) {
    InputStream inputStream;
    String result = "";
    try {
        arraylist = new ArrayList<HashMap<String, String>>();

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();


        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();
        Log.d("JsonStringSend", json);
        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if (inputStream != null) {
            result = convertInputStreamToString(inputStream);
            Log.d("JSONResponce", result);
            JSONObject jsonObj = new JSONObject(result);
            contacts = jsonObj.getJSONArray("Electronics");
            for (int i = 1; i < contacts.length()-1; i++) {
                JSONObject c = contacts.getJSONObject(i);
                String id = c.getString("Print");
                Log.e("Errrrrrrr",""+id);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    // 11. return result
    return result;
}


private String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line;
    inputStream.close();
    return result;

}

So the get the following error

Value {"Elec":"Cup1"} at 1 of type java.lang.String cannot be converted to JSONObject

Please help me

Thanks in advance

1
  • see my answer..... Commented Jul 23, 2016 at 5:54

4 Answers 4

2

This is the result after formatting your json in jsoneditoronline.org

enter image description here

Notice that the objects inside the 'Electronics' array are not JSONObject but String instead.

A simple workaround would be to get the object as a String first then parse it into a JSONObject like:

    // 10. convert inputstream to string
    if (inputStream != null) {
        result = convertInputStreamToString(inputStream);
        Log.d("JSONResponce", result);
        JSONObject jsonObj = new JSONObject(result);
        contacts = jsonObj.getJSONArray("Electronics");

        // Note contacts.length() NOT contacts.length() - 1
        for (int i = 1; i < contacts.length(); i++) {

            String cString = contacts.getString(i);
            JSONObject c = new JSONObject(cString);

            String id = c.getString("Print");
            Log.e("Errrrrrrr",""+id);
        }
    }

The best option would be however to correct the data returned from the server.

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

4 Comments

what is c string inside for loop
I have one ,more problem
what should i do when there are more values in electronic
@LoadMore What do you mean by 'more values'. The code will still work because you're iterating through and accessing the array by index.
0

for (int i = 1; i < contacts.length()-1; i++)

to

for (int i = 0; i < contacts.length(); i++)

Comments

0

Instead calling getString or getJsonObject use jsonObject.get(key) and check the instance like below.

Object obj = jsonObject.get(key);
if(obj instanceof String) {
   // retrieve the string
} else if(obj instanceof JsonObject) {
    // retrieve the Json object
}

To get the values from JsonObject use jsonObject.optString or .optJsonObject, instead jsonObject.getString or .getJsonObject.

Comments

0

Try this,

        String response = "{\"Electronics\":[\"{\\\"Elec\\\":\\\"Cup0\\\"}\",\"{\\\"Elec\\\":\\\"Cup1\\\"}\",\"{\\\"Elec\\\":\\\"Cup2\\\"}\",\"{\\\"Elec\\\":\\\"Cup3\\\"}\",\"{\\\"Elec\\\":\\\"Cup4\\\"}\",\"{\\\"Elec\\\":\\\"Cup5\\\"}\",\"{\\\"Elec\\\":\\\"Cup6\\\"}\",\"{\\\"Elec\\\":\\\"Cup7\\\"}\",\"{\\\"Elec\\\":\\\"Cup8\\\"}\",\"{\\\"Elec\\\":\\\"Cup9\\\"}\"],\"Printable\":[\"{\\\"Print\\\":\\\"Mug0\\\"}\",\"{\\\"Print\\\":\\\"Mug1\\\"}\",\"{\\\"Print\\\":\\\"Mug2\\\"}\",\"{\\\"Print\\\":\\\"Mug3\\\"}\",\"{\\\"Print\\\":\\\"Mug4\\\"}\",\"{\\\"Print\\\":\\\"Mug5\\\"}\",\"{\\\"Print\\\":\\\"Mug6\\\"}\",\"{\\\"Print\\\":\\\"Mug7\\\"}\",\"{\\\"Print\\\":\\\"Mug8\\\"}\",\"{\\\"Print\\\":\\\"Mug9\\\"}\"]}";

    try {

        JSONObject jsonObj = new JSONObject(response);
        JSONArray Electronics = jsonObj.getJSONArray("Electronics");
        JSONArray Printable = jsonObj.getJSONArray("Printable");

        for (int i = 1; i < Electronics.length(); i++) {

            String cString = Electronics.getString(i);
            JSONObject c = new JSONObject(cString);
            String Elec = c.getString("Elec");
            Log.e("Elec", "" + Elec);
        }

        for (int i = 1; i < Printable.length(); i++) {

            String cString = Printable.getString(i);
            JSONObject c = new JSONObject(cString);
            String Print = c.getString("Print");
            System.out.println(" Print --> " + Print);
        }
    } catch (Exception e) {

        System.out.println(" time error --> " + e.toString());
    }

Logcat,

07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup1 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup2 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup3 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup4 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup5 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup6 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup7 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup8 07-23 01:48:12.808 8134-8134/com.example.peacock.abc E/Elec: Cup9 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug1 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug2 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug3 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug4 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug5 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug6 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug7 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug8 07-23 01:48:12.808 8134-8134/com.example.peacock.abc I/System.out: Print --> Mug9

I hope u solve your problem soon....

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.