Can´t convert JSON to JSONObject - php

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.

Related

php server parse simple string using JSON to Android client

Hi i am quite new in Android client php server. I follow some tutorial for post and response variable by JSON but this reponse error. Value of type java.lang.String cannot be converted to JSONObject.
The JSON post is success but the response is error.
Android code:
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.1/databastest/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
resultLoging = jsonObject.getString("ResultArray");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
Toast.makeText(mContext, resultLoging, Toast.LENGTH_LONG).show();
if(exception != null){
Log.i("Error",exception.getMessage());
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
php code
mysqli_query($con,"INSERT INTO usersacc
(phone, password) VALUES('$pho', '$pass')");
#Build the result array (Assign keys to the values)
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
The insert is successful but the result not done.
Replace this your code with this may work.Get the response from server as Object not as String.
Object result = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(result.toString());
resultLoging = jsonObject.getString("ResultArray");

Receiving JSONObject in PHP

I am sending JSONObject to the server using below code. But I am unable to receive it in server side using PHP . Can anyone please guide me how to receive it.
public void sendStatus(JSONObject object) {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams);
String jsonString = object.toString();
try {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(jsonString);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
I have already done it using name value pair using following code
$datastring = trim($headers['name']);
But as in the above code I am only getting the JSONObject but not any tag. So please anyone can help me or provide me any useful link then I will be grateful.
My JSONObject format is as belos=w
{
"user_id": "123456",
"Objects": [
{
"name": "AAA"
},
{
"name": "BBB"
},
{
"name": "CCC"
},
{
"name": "DDD"
}
]
}
To send the JSON as string from the Android device you can send it as a POST param:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json_string", jsonString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
or if you want to send it as a header:
httppost.addHeader("json_string", jsonString)
However, a header has a maximum length so I'd recommend sending it as POST params
In order to work with a JSON object in PHP, you must decode it first into a associative array doing the following
$jsonAsArray = json_decode($jsonAsString, true)
Afterward, you'll be able to access JSON properties like:
$jsonAsArray['user_id'] // 123456
$jsonAsArray['Objects'][1]['name'] // BBB

Android org.json.JSONException: Cannot convert to JSON array

I am getting org.json.JSONException: Cannot convert to JSON array, heres the code:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://csddata.site11.com/json.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.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");
}
String read = sb.toString();
Log.d("HTTP", "Result = " + read);
return read;
} finally {
if (is != null) {
is.close(); // Makes sure that the InputStream is closed after the app is// finished using it.
}
}
Now code where im getting the error:
protected void onPostExecute(String result) {
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
MagList titleRow = new MagList();
titleRow.title = json_data.getString("first_name");
titleRow.page_url = json_data.getString("last_name");
arrayOfWebData.add(titleRow);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("HTTP", "Error parsing data "+e.toString());
Log.d("HTTP", "Failed data was:\n" + result);
e.printStackTrace();
} finally {}
}
I am receiving both "Log.d" and this is what i receive through them:
05-24 16:44:59.721: D/HTTP(20260): Error parsing data org.json.JSONException: Value [
05-24 16:44:59.721: D/HTTP(20260): { "firstName":"John" , "lastName":"Doe" },
05-24 16:44:59.721: D/HTTP(20260): { "firstName":"Anna" , "lastName":"Smith" },
05-24 16:44:59.721: D/HTTP(20260): { "firstName":"Peter" , "lastName": "Jones" }
05-24 16:44:59.721: D/HTTP(20260): ]; of type java.lang.String cannot be converted to JSONArray
05-24 16:44:59.721: D/HTTP(20260): Failed data was:
05-24 16:44:59.721: D/HTTP(20260): "[\n{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },<br> \n{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" }, \n{ \"firstName\":\"Peter\" , <br>\"lastName\": \"Jones\" }\n];"
Can anyone help? if you need any more info just leave a comment :)
PHP FILE:
<?php
$json = '[
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];';
print json_encode($json);
?>
AFTER CHANGES:
05-24 17:33:17.221: W/System.err(24203): org.json.JSONException: Value [
05-24 17:33:17.221: W/System.err(24203): {"firstName":"John","lastName":"Doe"},
05-24 17:33:17.221: W/System.err(24203): {"firstName":"Anna","lastName":"Smith"},
05-24 17:33:17.221: W/System.err(24203): {"firstName":"Peter","lastName": "Jones"}
05-24 17:33:17.221: W/System.err(24203): ] of type java.lang.String cannot be converted to JSONArray
05-24 17:33:17.221: W/System.err(24203): at org.json.JSON.typeMismatch(JSON.java:111)
05-24 17:33:17.221: W/System.err(24203): at org.json.JSONArray.<init>(JSONArray.java:91)
05-24 17:33:17.221: W/System.err(24203): at org.json.JSONArray.<init>(JSONArray.java:103)
05-24 17:33:17.221: W/System.err(24203): at com.example.android.navigationdrawerexample.MainActivity$DownloadWebpageTask.onPostExecute(MainActivity.java:381)
NEW CODE:
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try{
if(result != null) result = result.replace("\n","");
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
MagList titleRow = new MagList();
titleRow.title = json_data.getString("first_name");
titleRow.page_url = json_data.getString("last_name");
arrayOfWebData.add(titleRow);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("HTTP", "Error parsing data "+e.toString());
Log.d("HTTP", "Failed data was:\n" + result);
e.printStackTrace();
} finally {}
aa=new FancyAdapter();
listV.setAdapter(aa);
}
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://csddata.site11.com/json.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.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);
}
String read = sb.toString();
Log.d("HTTP", "Result = " + read);
return read;
} finally {
if (is != null) {
is.close(); // Makes sure that the InputStream is closed after the app is// finished using it.
}
}
}
}
I think the problem is that you are trying to json_encode a string that is already json encoded in your php code. Typically you call json_encode on a php array to reformat it as a json string. since it's already a string i believe you can simply echo($json); instead of trying to json_encode it.
you have following issues in current json String:
1. you will need to remove spaces from Json String in PHP code before passing it to json_encode. valid json string is:
$json = '[
{"firstName":"John","lastName":"Doe"},
{"firstName":"Anna","lastName":"Smith"},
{"firstName":"Peter","lastName": "Jones"}
]';
print $json;
2. no need to add new line character when reading data from BufferedReader :
String line = null;
while((line = reader.readLine()) != null){
sb.append(line); //<<< remove \n from here
}
This is because of the new line character (\n) in the string. Either remove it via replace from the string or don't return the response with "\n" character from your service. The JSONArray would work fine then.
EDIT: do this:
try{
if(result != null) result = result.replace("\n","");
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
MagList titleRow = new MagList();
titleRow.title = json_data.getString("first_name");
titleRow.page_url = json_data.getString("last_name");
arrayOfWebData.add(titleRow);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("HTTP", "Error parsing data "+e.toString());
Log.d("HTTP", "Failed data was:\n" + result);
e.printStackTrace();
} finally {}
}
EDIT2:
just noticed you are appending "\n" to your string builder. That is the error point. The other answer is bang on. No need to do replace in the string.
EDIT3:
replace with the following code. Remove all new line chars:
$json = '[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"}, {"firstName":"Peter","lastName": "Jones"}]';
print json_encode($json);

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.

Why I can't getting json in android?

I am having problem in getting one dimensional JSON please guide me where either the problem is in my JSON or in my code?
JSON:
{
"data": {
"id": "S000010",
"name": "ZS Solutions",
"email": "zswebs#gmail.com",
"phone": "051-1234567",
"address": "p.o.box 123",
"about": "im the company\r\nHAhahhaa"
}
}
Android activity JSON retrieval code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("abc.php?Id="+id+"");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse hresponse = httpclient.execute(httppost);
HttpEntity entity = hresponse.getEntity();
is = entity.getContent();
String result=co(is);
JSONObject json=new JSONObject(result);
JSONArray a= json.getJSONArray(data);
for (int i = 0; i <= a.length(); i++) {
json = a.getJSONObject(i);
String cname=json.getString("name");
String cemail=json.getString("email");
String cphone=json.getString("phone");
String caddress=json.getString("address");
String cabout=json.getString("about");
Log.w("DATA ","NAME "+cname+"E-mail "+cemail+"Phone "+cphone+"ADDRESS"+caddress+"ABOUT"+cabout);
}
}
catch(Exception e){}
JSONArray a= json.getJSONArray(data); <-- this causing the Exception as
data is not a json Array, instead , it is a JSONObject
Your code should be
JSONObject json=new JSONObject(result);
JSONObject jsonobj=json.getJSONObject("data");
String cname=jsonobj.getString("name");
String cemail=jsonobj.getString("email");
String cphone=jsonobj.getString("phone");
String caddress=jsonobj.getString("address");
String cabout=jsonobj.getString("about");

Categories