Android, JSONObject cannot be converted to JSONArray - php

In my Android app, I'm trying to communicate with a web server that holds randomly-generated fake usernames and scores.
{ scores: [
{
un: "Feltricapulta",
sc: "143"
},
{
un: "Henroid",
sc: "120"
},
{
un: "ieteubmospta",
sc: "70"
},
{
un: "pmbotesteuai",
sc: "67"
},
{
un: "epesomiubtat",
sc: "65"
}
] }
The code in the PHP file looks like this:
<?php
include ('connecttomysql.php');
$command = 'SELECT un, sc FROM xmlscores ORDER BY sc DESC';
$execute_command = mysql_query($command);
echo '{ "scores": ';
while ($table_row = mysql_fetch_assoc($execute_command))
{
$jsonArray [] = $table_row;
}
echo json_encode($jsonArray);
echo '}'
?>
I've called this .php URL in Android using the generic HttpGet method. The output of the json data prints to the stacktrace and provides me with the "Cannot convert from Object to Array" error.
Looking at the PHP file and the json output, is there anything noticeably wrong with my codes or the output? I can't figure it out.

"Cannot convert from Object to Array"
means you are trying to convert response string to JSONArray. but Current String Contains JSONObject as root element instead of JSONArray. so convert it to JSONObject as:
JSONObject json=new JSONObject(<Server response string here>);
// get scores JSONArray from json
JSONArray jsonscoresarray=json.getJSONArray("scores");
...

// Implementation of Json array should go like this.
#Override
public void fromJSON(Object json) throws JSONException {
JSONObject jsonObject = new JSONObject((String) json);
JSONArray jsonArray = jsonObject.getJSONArray("scores");
mScores = new ArrayList<Score>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjct = (JSONObject)jsonArray.getJSONObject(i);
Score object = new Score();
object.fromJSON(jsonObjct);
mScores.add(object);
}
}

Related

Receive JSON Output from PHP in Android

I am using this code in my PHP script:
echo json_encode($output);
and I get the following in my pages output:
[{"food_id":"1","food_description":"Free Range Egg","food_protein":"8"},{"food_id":"3","food_description":"Seeded Bread","food_protein":"6"}]
Can you please lead me the way on how I can receive the pages output in my Android Application and fit in in my object below? e.g.:
food.setFood_id(c.getInt("food_id"));
You need to do something like this..
JSONObject jsonObject = new JSONObject(response);// response is your json data which you are sending from php
JSONArray jsonArray = jsonObject.getJSONArray("mMessage");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
food.setFood_id(jsonObj.getInt("food_id"));
}
and from php side you need to send data like this
public function get_data()
{
$json_response = array();
$sql_querry_arry = array(); // array filled with sql result
$json_response['mMessage'] = $sql_querry_arry;
echo json_encode($json_response);
}
Now receive output as a string and follow the steps i mention before

ERROR converting from JSONArray to JSONObject processing Android

I'm having difficult with an error I keep getting when trying to process my JSON.
Value [] of type org.json.JSONArray cannot be converted to JSONObject is an error I keep getting and I don't know whats causing it.
The JSON is:
{
"recipe":[
{
"recipeID":"1",
"recipeName":"chicken salad",
"ingredients":"chicken lettuce tomato cucumber"
},
{
"recipeID":"2",
"recipeName":"banana shake",
"ingredients":"banana ice cream vanilla "
}
]
}
And what I'm doing to process it is:
JSONArray recipes = null;
try {
JSONObject jsonObj = new JSONObject(json);
recipes = jsonObj.getJSONArray("recipe");
HashMap<String, String> map = new HashMap<String, String>();
// looping through All recipes
for (int i = 0; i < recipes.length(); i++) {
JSONObject c = recipes.getJSONObject(i);
name = c.getString("recipeName");
}
But I keep getting this error :/
I see you are parsing the Json string by hand, you can do it, and it is quickly enough, but in my case I always use some type of library that do the job for me, so I will like to recommend you that take a look at Gson library from google.
https://code.google.com/p/google-gson/

JsonObject from PHP to Android + security

Hi everyone I have this php output.
//fetching all the rows from the query
$row = $stmt->fetchAll();
//output to json
die(json_encode($row));
[{"u_id":"8","id":"8","name":"test1","location_long":"10.01475","location_lati":"53.57823","description":"loo\nlol","date":"2014-11-21","time":"18:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"},
{"u_id":"8","id":"9","name":"test9","location_long":"10.01475","location_lati":"53.57823","description":"test9\n","date":"2014-11-21","time":"19:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"},
{"u_id":"8","id":"10","name":"test10","location_long":"10.01475","location_lati":"53.57823","description":"lol","date":"2014-11-22","time":"19:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"},
{"u_id":"8","id":"11","name":"lol","location_long":"10.01475","location_lati":"53.57823","description":"","date":"2014-11-24","time":"18:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"}]
Now I want get each item with its value into my listview item
Code:
JSONObject json = jsonParser.makeHttpRequest(
EVENTS_URL, "POST", params);
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length();i++)
{
adapter.add(new DataProvider(own_event,
jsonArray.getJSONObject(i).getString("description"),
jsonArray.getJSONObject(i).getString("name"),
jsonArray.getJSONObject(i).getString("date"),
jsonArray.getJSONObject(i).getString("time"),
jsonArray.getJSONObject(i).getDouble("location_long"),
jsonArray.getJSONObject(i).getDouble("location_lati"),
jsonArray.getJSONObject(i).getInt("id")));
}
Now I get this error:
Error parsing data org.json.JSONException: Value [] of type
org.json.JSONArray cannot be converted to JSONObject
In the line where I create the JSONArray jsonArray.
I never worked with json before so, is there a better way to parse the data from my php file to android, and a more secure way in doing that?
Server response is came in JSONArray so no need to convert in JSONObject just build JSONArray from server response and return as JSONArray instead JSONObject from makeHttpRequest :
JSONArray jsonArray = jsonParser.makeHttpRequest(EVENTS_URL, "POST", params);

Can´t convert JSON to JSONObject

Here´s the JSON that my php file delivers:
[{"id":"408","punktezahl":"15","name":"testname","email":"hsksjs","datum":"24.01.14 17:11","wohnort":"Vdhdhs","newsletter":"J"}]
When I try to access the JSON Object like this
public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
Thread t = new Thread(){
#Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("output");
String name = userDetails.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
}
}catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
I get the following error:
01-24 18:18:21.746: W/System.err(20673): org.json.JSONException: Value [{"id":"408","datum":"24.01.14 17:11","punktezahl":"15","email":"hsksjs","newsletter":"J","wohnort":"Vdhdhs","name":"testname"}] of type org.json.JSONArray cannot be converted to JSONObject
01-24 18:18:21.746: W/System.err(20673): at org.json.JSON.typeMismatch(JSON.java:111)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:159)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:172)
01-24 18:18:21.746: W/System.err(20673): at com.wuestenfest.jagdenwilli.Highscore_zeigen$1.run(Highscore_zeigen.java:82)
Where´s my mistake?
Your response is a JSONArray not a JSOnObject.
So change
JSONObject parentObject = new JSONObject(response);
to
JSONArray jsonarray = new JSONArray(response);
Your JSON
[ // json array node
{ // jsson onject npode
"id": "408",
"punktezahl": "15",
"name": "testname",
"email": "hsksjs",
"datum": "24.01.14 17:11",
"wohnort": "Vdhdhs",
"newsletter": "J"
}
]
I do not see any json object output either in the above json. So
JSONObject userDetails = parentObject.getJSONObject("output");
is also wrong.
Parsing
JSONArray jsonarray = new JSONArray(response);
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");
The problem is just as the exception describes: you are trying to parse your response object into a JSONObject, but it is actually a JSONArray (as seen by the square brackets). In stead, parse it as a JSONArray, and get the first element from the array, which would be your desired JSONObject.

trying to get json object from php to android

i am trying to parse an array from my php script to my android app.
my android code
public void func4(View view)throws Exception
{final String TAG_CONTACTS = "response";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc3.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try
{
JSONArray jArray = new JSONArray(response.toString());
// JSONObject jsonObject = new JSONObject(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
User_List.add(json_data.getString(TAG_CONTACTS));
String s = User_List.get(0).toString();
tx.setText(s);
}
}
catch (Exception e)
{
tx.setText((CharSequence) e);
}
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
now i am sending or ECHOing a jSON array from my php code, which is being read into the response object of string type.
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
echo json_encode($cars);
exit;
?>
now error i am getting is org.json.JSONException: Value Volvo at 0 of type java.lang.String cannot be converted to JSONObject
i think thar onSuccess func accept string parameter and i m sending json as a parameter to it.. thats what causing problem please help.
Try Like this
JSONObject json = jsonParser.makeHttpRequest(url_get_contact, "GET", params);
Log.d("All Groups: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
groups = json.getJSONArray(TAG_GROUP);
System.out.println("Result Success+++"+groups);
for (int i = 0; i < groups.length();i++) {
JSONObject c = groups.getJSONObject(i);
String name = c.getString(TAG_CONTACTS);
System.out.println("Checking ::"+name);
namelist.add(name); // namelist is ur arraylist
}
}else {
showAlert();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
Let me know ur problem solved or not...
Answer found, i guess i was trying to convert an already String converted object from json into string again.
well to be precise i ust deleted JSONObject json_data = jArray.getJSONObject(i);
and it worked for me. Now i am able to save all values in my array.

Categories