json object cannot be converted to jsonarray in android - java

01-16 08:16:19.210: W/System.err(1394): org.json.JSONException: Value
{"GetDoctorsListResult":[
{"Name":"Sujay Sharma","DoctorID":154,"Clinics":null,"speciality":"Allergy and immunology","Locality":"Mumbai","Address":"Abcc Building "}
,{"Name":"Samir Tapiawala","DoctorID":159,"Clinics":null,"speciality":"Homeopath","Locality":"Mumbai","Address":"57\/101, Jawahar Nagar RD. NO. 6, GOREGAON WEST "}
,{"Name":"Sahil Kuma","DoctorID":171,"Clinics":null,"speciality":"Aerospace Medicine","Locality":"Mumbai","Address":"Digvija "}
,{"Name":"Himesh Jagtap","DoctorID":180,"Clinics":null,"speciality":"Bariatric Surgery","Locality":"Mumbai","Address":"Abc- Society "}
,{"Name":"Aarnav Prabhudesai","DoctorID":190,"Clinics":null,"speciality":"Dentistry","Locality":"Mumbai","Address":"Joyvilla Jawahar Nagar "}
,{"Name":"Neeharika Saxana","DoctorID":197,"Clinics":null,"speciality":"Gynaecologist","Locality":"Mumbai","Address":"Joyvilla, Jawahar Nagar "}
,{"Name":"Neeharika Saxena","DoctorID":205,"Clinics":null,"speciality":"Gynaecologist","Locality":"Mumbai","Address":"Joyvilla "}
,{"Name":"Ravi Sharma","DoctorID":207,"Clinics":null,"speciality":"Ayurvedacharya","Locality":"Mumbai","Address":"Q\/02 "}
,{"Name":"Prashant Bhatt","DoctorID":209,"Clinics":null,"speciality":"Dentistry","Locality":"Mumbai","Address":"202 Anand Vihar , Bldg No-2 , D-wing , Bhawani Chowk , b--cabin Road , Ambernath(e). Bhawani Chowk"}
,{"Name":"Samidha Sen","DoctorID":210,"Clinics":null,"speciality":"Addiction Medicine","Locality":"Mumbai","Address":"S\/09 "}
,{"Name":"Subodh Mehta","DoctorID":212,"Clinics":null,"speciality":"Orthopaedic Surgery","Locality":"Mumbai","Address":"Opera "}]} of type org.json.JSONObject cannot be converted to JSONArray
here is my activity code:
class DownloadTask extends AsyncTask<String, Void, Object> {
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(4000); // Do your real work here
} catch (InterruptedException e) {
e.printStackTrace();
}
return true; // Return your real result here
}
protected void onPostExecute(Object result) {
// Pass the result data back to the main activity
DoctorSearchActivity.this.data = result;
if (DoctorSearchActivity.this.progressdialog != null) {
DoctorSearchActivity.this.progressdialog.dismiss();
}
try {
JSONStringer geneology = new JSONStringer()
.object().key("Params").object().key("TypesOnSearch")
.value("name").key("CharactersToSearch")
.value("s")
.endObject();
JSONArray results = new JSONArray();
results = BC
.returnJSONArray(geneology,
"http://192.168.2.27/HYEHR_WCFService/DoctorService.svc/GetDoctorsList");
if (results.length() == 0) {
Toast.makeText(
DoctorSearchActivity.this,
"Error Occured while loading data.Try again later.",
Toast.LENGTH_LONG).show();
}
// for (int i = 0; i < results.length(); i++) {
// Log.v("data", results.getString(i));
// }
// aTable = BC.appendRows(aTable, results,
// DoctorSearchActivity.this);
} catch (Exception e) {
// TODO: handle exception
}
}
}
and my json function
:
public JSONArray returnJSONArray(JSONStringer JsonString, String url) {
results = new JSONArray();
try {
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
StringEntity entity = new StringEntity(JsonString.toString());
request.setEntity(entity);
Log.v("data", request + JsonString.toString());
// Log.v("data sender",request.setEntity(entity));
// Send request to WCF service
DefaultHttpClient httpClient1 = new DefaultHttpClient();
HttpResponse response = httpClient1.execute(request);
Log.v("response code", response.getStatusLine().getStatusCode()
+ "");
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
results = new JSONArray(new String(buffer));
Log.v("results length : ", results.length() + "");
}
catch (Exception e) {
// i mean sending data without key
// TODO: handle exception
e.printStackTrace();
}
return results;
}
I am getting this error i am passing data in jsonobject and receiving data in jsonarray.

Try to replace this:
results = new JSONArray(new String(buffer));
by this:
results = new JSONObject(new String(buffer)).getJSONArray("GetDoctorsListResult");

The root element of the JSON from URL is a JSONObject you should first parse it to JSONObject and then
get GetDoctorsListResult which is an array from the object.

I think your First Element of object GetDoctorsListResult is JSON array . So you have to take its value in json array.
REFER THIS THREAD and THIS ONE
JSONArray DoctorsList= jsonResponse.getJSONArray("GetDoctorsListResult");

HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jsonObject=new JSONObject(result);
JSONArray jsonArray=jsonObject.getJSONArray("GetDoctorsListResult");
use this code after getting response.

Related

Java parsing json array, Error parsing data org.json.JSONException

This is my code, in my log, i'm getting:
E/JSON Parser: Error parsing data org.json.JSONException Value xml of type java.lang.String cannot be converted to JSONObject
I really need a solution i have been searching for weeks now.
#Override
protected String doInBackground(String... para) {
List<NameValuePair> params=new ArrayList<NameValuePair>();
JSONObject json=jparser.makeHttpRequest(getDataUrl, "POST", params);
try {
success=json.getInt("success");
if(success==1){
drivers=new ArrayList<Driver>();
JSONArray sounds=json.getJSONArray("location");
for (int i = 0; i < sounds.length(); i++) {
JSONObject jobj=sounds.getJSONObject(i);
Driver d=new Driver();
d.setId(jobj.getString("id"));
d.setName(jobj.getString("name"));
d.setEmail(jobj.getString("email"));
d.setNumber(jobj.getString("number"));
d.setLatitude(jobj.getString("latitude"));
d.setLongitude(jobj.getString("longitude"));
d.setInfo(jobj.getString("info"));
d.setCost(jobj.getString("cost"));
drivers.add(d);
}
}
} catch (JSONException e) {
e.printStackTrace();
error=1;
}catch (Exception e) {
error=1;
}
return null;
}
And this is the JSONParser class
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if(method.equals("GET")) {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 JSON String
return jObj;
}
}
PHP File
<?php
header('Content-Type: application/json');
$response = array();
// include db connect class
require_once 'core/db_connect.php';
$db = new DB_CONNECT();
$sql="SELECT * FROM locations WHERE online=1";
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error($db->connect()));
if (mysqli_num_rows($result)>0) {
$response["location"] = array();
while ($row=mysqli_fetch_array($result)) {
$files=array();
$files["id"]=$row["id"];
$files["name"]=$row["name"];
$files["email"]=$row["email"];
$files["number"]=$row["number"];
$files["latitude"]=$row["latitude"];
$files["longitude"]=$row["longitude"];
$files["info"]=$row["vehicleinfo"];
$files["cost"]=$row["costpkm"];
array_push($response["location"], $files);
}
$response["success"]=1;
echo json_encode($response);
} else {
$response["success"]=0;
$response["message"]="No Taxi found";
echo json_encode($response);
}
?>
Based on your error, the return result for makeHttpRequest is an xml object instead of json formated string.
Solved
the error was due to incorrect url, the xampp apache server was returning an object not found page..error 404, which is an xml file. That's why the return result for makeHttpRequest is an xml object instead of json formated string.

Get Json data from the Url below(Url returns json data)

This is the URL which returns me the json object Link.
Now I need to get the json data to my code. When I try to access the link I get the html script. How do I get the json data from the above URL to my code. Here is my code.
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new
`ProgressDialog(MainActivity.this);`
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select1 = "http://andpermission.byethost5.com/PermissionList.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select1);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
//Toast.makeText(MainActivity.this, "Please Try Again", Toast.LENGTH_LONG).show();
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String db_detail="";
if(et.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
}
//text_1.append(id+"\t\t"+name+"\t\t"+password+"\t\t"+"\n");
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Using string builder I append the content and I find only the java script and I don't find the json data. How to I get the json data from the above URL.
In string "Result" in my code I get the below output.
<html>
<body>
<script type="text/javascript" src="/aes.js"></script>
<script>
function toNumbers(d) {
var e = [];
d.replace(/(..)/g, function(d) {
e.push(parseInt(d, 16))
});
return e
}
function toHex() {
for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
return e.toLowerCase()
}
var a = toNumbers("f655ba9d09a112d4968c63579db590b4"),
b = toNumbers("98344c2eee86c3994890592585b49f80"),
c = toNumbers("b8eeb5e790c4a5395d01cde6b8230fdd");
document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
location.href = "http://andpermission.byethost5.com/PermissionList.php?ckattempt=1";
</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
How do I get only the json data from the URL instead the java script.
Try the full URL: http://andpermission.byethost5.com/PermissionList.php?ckattempt=1.
And also make sure you are using GET instead of POST, because that's what the URL refers to.
Here a good example: http://www.learn2crack.com/2013/10/android-json-parsing-url-example.html
On the other hand, there are some libraries like Aquery, Okhttp and Volley, that do this job very good.

Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject in android?

I am trying to access a json array from android. But it shows an exception. This is my android code used for retrieving the json array:
protected void showList(){
final String TAG_RESULTS="result";
final String TAG_USERNAME="username";
final String TAG_NAME = "message_recd";
final String TAG_ADD ="message_sent";
ArrayList<HashMap<String, String>> personList;
personList = new ArrayList<HashMap<String,String>>();
//for tesitng
JSONObject jObject=null;
//
try {
//for testing
//
JSONObject json = new JSONObject(myJSON);
JSONArray peoples =json.getJSONArray("emparray");
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
name = c.getString("user_id");
address = c.getString("crtloc_lat");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("user_id",name);
persons.put("crtloc_lat",address);
personList.add(persons);
Toast.makeText(MapsActivity.this, "woow id"+name, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("errore",e.toString());
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("username", fName));
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abh.netai.net/abhfiles/searchProfession.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
php file
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=0;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($con);
?>
and the json array
[[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769566","crtloc_lng":"72.361031"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]
the error it show me is this
Value [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769749","crtloc_lng":"72.361168"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}] of type org.json.JSONArray cannot be converted to JSONObject
It is giving you this error because the first object in the array is not a JSONObject but an JSONArray following 4 JSONObjects.
[
[],
{
"user_id": "77",
"crtloc_lat": "34.769638",
"crtloc_lng": "72.361145"
},]
As you can see you expect it to always be a JSONObject.
JSONObject c = peoples.getJSONObject(i);
Anticipate on that first JSONArray in the list.

JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject

Guys can you help me a little bit, Im getting this error:
"JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject"
When I'm parsing the data here is my code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Here is the code where I'm instantiating the Parser:
private void fillSpinnerCabTypes() {
List<String> cabTypesSpinner = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
JSONObject cabTypesObject = jsonParser.getJSONFromUrl(urlTypeCabs);
try{
TypesArray = cabTypesObject.getJSONArray(TAG_TYPES);
for(int i = 0; i < TypesArray.length(); i++){
JSONObject c = TypesArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
cabTypesSpinner.add(name);
}
}catch(Exception e ){
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cabTypesSpinner);
final Spinner spnCabTypes = (Spinner)findViewById(R.id.spnTypeOfCab);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spnCabTypes.setAdapter(adapter);
}
I'm really stuck with this. I'm populating the spinner from a database in a backend on Django in the server.
This is my JSON data
{"Types": [{"name": "Normal"}, {"name": "Discapacitados"}, {"name": "Buseta"}]}
This issue comes from the server.
The URL you're requesting, send you back data but not in the JSON format.
The Exception you get is telling you that the String the server send you back starts with:
<!DOCTYPE
This can be:
A simple webpage (instead of raw JSON). It correspond to the first XML tag of a web page (source)
An error page generated by the server, and printed in HTML
To debug this further, simply print the content of your json variable in the logcat:
Log.d("Debug", json.toString());
jObj = new JSONObject(json);
This problem came in my code also.and solution was different.It occured due to spelling mistake of webservice.
Solution 1:
for example real the url is
http://example.com/directory/file.php
and i had used
http://example.com/directory/file1.php
Solution 2:
use loopj library .it exactly gives you the explained error.
AsyncHttpClient client = new AsyncHttpClient();
client.post(str , localRequestParams, new AsyncHttpResponseHandler() {
#Override
public void onFinish() {
super.onFinish();
Log.i("onFinish","onFinish");
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i("onSuccess","onSuccess");
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i("onFailure","onFailure");
}
});

Grabbing JSON content with Java

Here is a sample of my json_encode in PHP:
print(json_encode($row));
leads to {"AverageRating":"4.3"} which is good.
But in Java, I can not seem to grab this 4.3 value. Here it is (for an Android project) I have edited non-relevant data.
public class Rate extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
String Item, Ratings, Review, starAvg;
RatingBar ratingsBar;
ArrayList<NameValuePair> param;
public void onCreate(Bundle savedInstanceState) {
starAvg = "0"; // Sets to 0 in case there are no ratings yet.
new starRatingTask().execute();
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
class starRatingTask extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/average_stars.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", Item));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String starAvgTwo = null;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
starAvg = json_data.getString("AverageRating");
starAvgTwo = starAvg;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Star Ratings!",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
Toast.makeText(getBaseContext(), starAvgTwo,
Toast.LENGTH_LONG).show();
ratingsBar.setRating(Float.valueOf(starAvg));
}
}
That second toast produces a blank (I assume a "" - empty string?). If I change the toast variable back to starAvg, then it toasts "0".
How can I retrieve the value of 4.3.
As we discussed in the comments on the original question, the PHP is sending down as single JSONObject rather than an array. Parsing as a JSONObject is required in it's present state; however, if you begin sending down an array of your value objects, then you'd use JSONArray to parse it.
I think your JSON doesn't contain array. so just do this:
JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable
and try toast the averageRating.
and how to get the array from JSON object?
if you have JSON:
{"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }]
}
then use this code
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}
that code will produce
John Anna Peter
in your LogCat

Categories