java - org.json.JSONObject cannot be converted to JSONArray when receiving JSON code on Android App
I am trying to read JSON data from a localhost PHP file. It successfully connects but I get the error
05-27 15:40:24.108: E/log_tag(17146): Error Parsing Data org.json.JSONException: Value {"firstName":"John","lastName":"Doe"} of type org.json.JSONObject cannot be converted to JSONArray
When I open the PHP script in my browser it successfully displays{ "firstName":"John" , "lastName":"Doe" }
package com.example.testexternaldatabase;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
StrictMode.enableDefaults(); // STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.textView1);
getData();
}
public void getData() {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mstreetllc.com/Lab.asp"); // YOUR PHP
// SCRIPT
// ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Couldnt connect to database");
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "Name : " + json.getString("name") + "\n"
+ "Email : " + json.getString("email") + "\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
}
Any ideas on how I can fix this? Thanks.
Answer
Solution:
You're trying to convert what is considered a JSONObject directly into a JSONArray, which is throwing the error you're getting.
A JSONObject would start and and with the brackets { and }, respectively. A JSONArray would start and end with [ and ], respectively, as well as be deliminated by commas, similar to the fields in a JSONObject.
E.g. JSONObject:
E.g JSONArray containing 2 of your original objects inside a JSONObject:
Now, to fix your code, since you're only receiving a single JSONObject:
If you're actually returning an array of data (or if that's your intention), it will still be wrapped inside a JSONObject, and would have to be adjusted like so:
And inside your PHP Script, you would want to encode like so:
Don't forget to replace the variable names with whatever you're actually using, and hopefully I was descriptive enough without comments.
Answer
Solution:
You can do this :