0

$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array

This is Import libraries

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp" >
</ListView>

Internet Permission is Here

<uses-permission android:name="android.permission.INTERNET" />

error Please give me Answer How to get Multiple Values Using this Code and show into my ListView

This Is my MainActivity.java class file.

public class MainActivity extends Activity
{
    private String jsonResult;
    private String url = "YOUR_PHP_FILE_URL";
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView1);
        accessWebService();
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu)
     {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
     }

     // Async Task to access the web
     @SuppressLint("NewApi")
    private class JsonReadTask extends AsyncTask<String, Void, String>
     {
         @Override
         protected String doInBackground(String... params) 
         {
             HttpClient httpclient = new DefaultHttpClient();
             HttpPost httppost = new HttpPost(params[0]);
             try
             {
                 HttpResponse response = httpclient.execute(httppost);
                 jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
             }
             catch (ClientProtocolException e) 
             {
                 e.printStackTrace();
             } 
             catch (IOException e)
             {
                 e.printStackTrace();
             }
             return null;
         }

         private StringBuilder inputStreamToString(InputStream is) 
         {
             String rLine = "";
             StringBuilder answer = new StringBuilder();
             BufferedReader rd = new BufferedReader(new InputStreamReader(is));

             try 
             {
                 while ((rLine = rd.readLine()) != null)
                 {
                     answer.append(rLine);
                     Log.d(answer.toString(), "String Builder Class in IF Loop");
                 }
             }
             catch (IOException e)
             {
                 // e.printStackTrace();
                 Toast.makeText(getApplicationContext(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
                 Log.d(answer.toString(), "String Builder Class in Else Part");
             }
             return answer;
         }

         @Override
         protected void onPostExecute(String result)
         {
             ListDrwaer();
         }
     }// end async task

     public void accessWebService()
     {
         JsonReadTask task = new JsonReadTask();
          // passes values for the urls string array
          task.execute(new String[] { url });
     }

     // build hash set for list view
     public <jsonResult> void ListDrwaer() 
     {
         ArrayList<Map<String,String>> userList = new ArrayList<Map<String, String>>();
         Log.d(userList.toString(), "Starting JSONObject");

         try 
         {             
             Log.d("Starting Try Block", "Before JSONObject");

             JSONObject jsonResponse = new JSONObject(jsonResult);
             JSONArray jsonMainNode = jsonResponse.getJSONArray("user_info");

             Log.d(jsonMainNode.toString(), "Starting JSONObject");

             for (int i = 0; i < jsonMainNode.length(); i++) 
             {
                 JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                 String id = jsonChildNode.optString("Id:");
                 String name = jsonChildNode.optString("Name:");
                 String email = jsonChildNode.optString("Email:");
                 String phone = jsonChildNode.optString("Phone:");
                 String password = jsonChildNode.optString("Password");
                 String outPut = id + "-" + name+ "-" + email+ "-" + phone+ "-" + password;
                 userList.add(createEmployee("user_info", outPut));
                 Log.d(jsonChildNode.toString(), "Starting JSONObject inside For Loop");
             }
         } 
         catch (JSONException e)
         {
             Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show();
             Log.e("log_tag", "Failed data was:\n" + jsonResult);
         }

         SimpleAdapter simpleAdapter = new SimpleAdapter(this, userList,android.R.layout.simple_list_item_1,new String[] { "user_info" }, new int[] { android.R.id.text1 });
         listView.setAdapter(simpleAdapter);
     }

     private HashMap<String, String> createEmployee(String name, String number) 
     {
      HashMap<String, String> employeeNameNo = new HashMap<String, String>();
      employeeNameNo.put(name, number);
      return employeeNameNo;
     }
}
3
  • 1
    Probably trying to convert JSONArray to JSONObject. show jsonResult String also with Question Commented Jan 28, 2016 at 6:12
  • Could you post the complete error log ?. As @ρяσѕρєяK noted, You might be trying to convert JSONArray to JSONObject or may be some other format of text, such as html. I had the same problem, where i tried to parse some 404 html message to JSONObject. :) Commented Jan 28, 2016 at 6:24
  • Add your LogCat result Commented Jan 28, 2016 at 6:46

2 Answers 2

1

ok the error you are getting is very generic, error itself tells what you are doing wrong

$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array,

I believe you have string in the JSON data, "dummy data" as it is in double quotes which you are trying to read as a JSONObject. It is not a JSONObject but a String primitive type,

while parsing JSON you need to pay attention to what is a Object, Array and primitive-type

JSONObject 

will always be enclosed in { } so this represents that data inside a parentheses is a JSONObject, Example===>

JSONObject json = jsonArray.getJSONObject(i) 

or

 JSONObject json = new JSONObject("JSON DATA");


JSONArray 

will always be enclosed in [ ] so this represents that data inside a square bracket is a JSONArray, Example==> `json.getJSONArray("name of jsonArray");

Primitive-type

Boolean would like this

"isSelected":true
or
"isSelected":false

Integer would like this

"someInt":12

String would like this

"someString":"String value" 

as you can see where your problem is, you need to distinguish between JSON String from JSON Object

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

Comments

0

Remove this line because you convert Json String to Json Object

 JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

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.