ERROR converting from JSONArray to JSONObject processing Android - php

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/

Related

in android jsonarray cannot be converted in jsonobject

The script fetches data from phpmyadmin but android studio cause this error
of type org.json.Jsonarray cannot be converted to jsonobject
my code android
code
Actually you are getting JSONArray instead of JSONObject from your server. So, You have to parse the array first then you can get object from it.
JSONArray jsonArray = new JSONArray(response);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String m_e = jsonObject.getString("M_E");
}

how to convert the output of a PHP into a string to be used in Android?

I have a .php file on the server side that works fine and extracts me results with PDO method. Therefore, when I click the file on the browser, I have no problem.
Yet, I would like this output to be put in a textView in my Android app.
Now, by the end of the php file i added:
print(json_encode(array($output)));
while in MainActivity.class I tried to get this output by parsing it through JSON.
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
}
TextView.setText(s);
Now, how do I end the JSONObject, so that "s" becomes a String that can later be added to the TextView?
Thanks in advance
Try this.
String s="";
JSONArray jArray = result.getJSONArray(result);
for(int i=0 ; i < jArray.length() ; i++) {
JSONObject json = jArray.getJSONObject(i);
s = s+"Price : "+json.getString("Price");
}
TextView.setText(s);

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);

Android, JSONObject cannot be converted to JSONArray

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

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