45827

parssing JSONException: A JSONArray text must start with '[' at character 1

Question:

I'm trying to connect Android app with local MySQL database, but I have a problem in parsing JSON array. (I read all similar questions here, but nothing works.)

the error message:

Error parsing data org.json.JSONException: A JSONArray text must start with '[' at character 1 of [{"UserName":"Admin","Password":"111","Role":"0"},{"UserName":"Employee","Password":"123","Role":"1"}]

this is the the code:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new Connect().execute(); } private class Connect extends AsyncTask<Void, Void, String> { private String result = ""; private InputStream is = null; private ProgressBar progress_Bar; protected void onPreExecute() { progress_Bar = ((ProgressBar) findViewById(R.id.progress)); progress_Bar.setVisibility(0); } @Override protected String doInBackground(Void... params) { try { ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://10.0.2.2/users.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // convert response to string try { 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); } is.close(); result = sb.toString(); result.trim(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return result; } protected void onPostExecute(String result) { String name; try { Log.d("RESULT", result); JSONArray jArray = new JSONArray(result); JSONObject json_data = null; for (int i = 0; i < jArray.length(); i++) { json_data = jArray.getJSONObject(i); Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } } }

and this is the PHP code:

<?php $con1=mysql_connect("localhost", "root", ""); mysql_select_db("sehaty"); mysql_query("SET NAMES utf8"); $sql = mysql_query("SELECT * FROM users"); while($row = mysql_fetch_assoc($sql)) { $output[]=$row; } $data = json_encode($output); print($data); mysql_close(); ?>

Answer1:

Maybe your data is not valid because there are leading/trailing spaces/newlines/...

I would preprocess result in onPostExcecute(...) like this:

private final static String TAG = "YourApplication"; public static String asHex(String str) { byte[] buf = str.getBytes(); final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); char[] chars = new char[2 * buf.length]; for (int i = 0; i < buf.length; ++i) { chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4]; chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F]; } return new String(chars); } protected void onPostExecute(String result) { try { result = result.replaceAll("[\n\t]", "").replaceAll("[^ A-Za-z0-9\",\[\]{}]", "").trim(); Log.d(TAG, "RESULT: #" + result + "#"); Log.d(TAG, "RESULT: " + asHex(result)); JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { Log.d(TAG, "USERS: " + jArray.getJSONObject(i).toString()); } } catch (JSONException e) { Log.e(TAG, "ERROR: " + e.toString()); } }

Answer2:

the json you posted is valid. The issu could be related to how you read from the input stream

try changin this

try{ 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); }

to

int read = 0; int BUFFER_LEN = 32768; byte[] buffer = new byte[BUFFER_LEN]; while ( (read = is.read(buffer, 0, BUFFER_LEN)) >= 0) { sb.append(new String(buffer, 0, read)); } is.close();

Answer3:

Try with part of my code:

// Execute HTTP Post Request

HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent();

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(); result=sb.toString();

JSONArray jArray = new JSONArray(result); JSONObject json_data= new JSONObject();

for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); }

Answer4:

try this:

firsts in the request code:

ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); result = out.toString();

and int the parsing:

JSONArray jArray = new JSONArray(result); JSONObject json_data = null; String s = ""; for (int i = 0; i < jArray.length(); i++) { s = jArray.get(i).toString(); json_data = new JSONObject(s); Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show(); }

try setting the result JSON to "{result:[{"UserName":"Admin","Password":"111","Role":"0"},{"UserName":"Employee"‌​,"Passwo‌​rd":"123","Role":"1"},{"UserName":"x","Password":"x","Role":"-1"}]}" and in the parsing:

JSONObject json = new JSONObject(result); JSONArray jArray = json.getJSONArray("result"); JSONObject json_data = null; String s = ""; for (int i = 0; i < jArray.length(); i++) { s = jArray.get(i).toString(); json_data = new JSONObject(s); Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show(); }

Recommend

  • Exception in Runtime Permissions
  • Show/Hide the Custom ListView in android
  • I/O error during system call, Connection reset by peer issue with S3 client
  • Android Generic AsyncTask Class
  • Get data from WebApi in c#
  • Xamarin Android Request to Server is not establishing instead getting an exception?
  • Calling REST service with domain credentials from .NET 4.5 HttpClient
  • SlidingTabLayout: replace with fragment
  • Getting “A From phone number is required” in JSON call to Twilio
  • Openejb rest integration tests with exception mappers
  • Java AsyncTask passing variable to main thread
  • Ignoring a field without modifying the POJO class with Jackson
  • AlarmManager is blocking main thread
  • Composer error [UnexpectedValueException]
  • Running a Service from ASyncTask or Thread?
  • Sorting a HashMap, while keeping duplicates
  • how to avoid the dependencies hell with unit test in angular 2+
  • WSO2 ESB 4.0.3 - Error installing Data Services feature from 4.0.* repositories
  • How to apply async task into this
  • How to make http call with file in groovy to upload a file and build arguments
  • Rails 3, Custom Actions, and HTML request methods
  • dismiss Progress Dialog in another Activity … Android
  • How to synchronize two scrollview in Android?
  • Wrap C++ function using Boost Reflect or another C++ reflection library
  • How do you create a Fuseki SPARQL server using the Apache Jena Java API?
  • You tube videos are not playing
  • android Navigation Bar hiding and persantage of usable screen overlap
  • drawing random circles, storing their coorindates in an array
  • Primefaces ManyCheckbox inside ui:repeat calls setter method only for last loop
  • Sending cookie value via httpget but not getting the desired response
  • Rails Find when some params will be blank
  • Seeking advice on Jetty HttpClient Hang
  • how to do an event when i swipe from fragment to the other
  • Update CALayer sublayers immediately
  • JFileChooser in front of fullscreen Swing application
  • File upload with ng-file-upload throwing error
  • unknown Exception android
  • Can't mass-assign protected attributes when import data from csv file
  • failed to connect to specific WiFi in android programmatically
  • How do I use LINQ to get all the Items that have a particular SubItem?