If the response of a request is a json response how to handle it and decode it.I have tried the following abnd get an error # JSONArray json = new JSONArray(r1);
HttpPost post = new HttpPost(postURL);
MultipartEntity reqEntity = new MultipartEntity();
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
String r1 = EntityUtils.toString(resEntity);
System.out.println("printing response now "+r1);
JSONArray json = new JSONArray(r1);
//Toast.makeText(getApplicationContext(), "data received"+r1, Toast.LENGTH_LONG).show();
// JSONObject json = new JSONObject(r1);
JSONArray venues = json.getJSONObject("data")
.getJSONArray("url")
.getJSONObject(0)
.getJSONArray("url");
Json structure is given below
[
{"data":
{"url":
{
"url": "http://www.xxxxxx.com/story.html", "title":"some data","source_url": "www.somesite.com", "summary": "\n \n \n \n \n somedata again"
}
}
}
]
Error:
08-18 16:30:22.907: INFO/System.out(1178): Exceptionorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray
I've this following code taking your json and it works for me...
May be you've to check if your orginal json string is ok ... byte per byte may be .. invisible character may disturb the parsing
String r1 = "[{\"data\": {\"url\": { \"url\": \"http://www.xxxxxx.com/story.html\", \"title\":\"some data\",\"source_url\": \"www.somesite.com\", \"summary\": \"\\n \\n \\n \\n \\n somedata again\"}}}]";
try {
JSONArray json = new JSONArray(r1);
Object url = json.getJSONObject(0)
.getJSONObject("data")
.getJSONObject("url")
.get("url");
Toast.makeText(getApplicationContext(), "url="+url.toString(), Toast.LENGTH_LONG).show();
Log.i("TESTJSON","All Is Ok");
} catch (Exception e) {
Log.d("TESTJSON","Something wrong..",e);
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
Related
Hello im trying to convert some JSON data into an array, I have dont it this way before but without objects
http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson
Here is the code that gets the data and trys to convert it
public JSONArray getQaukes()
{
String url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.d("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
This is what i get
http://pastebin.com/HVnx3gsq
Anyone know how I could find the correct way to do this?
Thanks
The result is a JSONObject not JSONArray.
Instead of JSONArray jsonArray = new JSONArray(entityResponse);
You should have JSONObject jObj = new JSONObject(entityResponse);
Edit: As an example, if you were to extract "features" Array, then you should do it like that:
//First of all - create JSON Object which you are going to parse (deserialize JSON string)
JSONObject jsonObj = new JSONObject(entityResponse);
// Extract JSON array from Object
JSONArray jsonArray = jsonObj.getJSONArray("features");
Your JSON string has many different elements, that is why you need to create JSON object, then extract arrays from it and so on. Until the very last token.
"type":"FeatureCollection",
"metadata":{
"generated":1452461493000,
"url":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson",
"title":"USGS Magnitude 1.0+ Earthquakes, Past Day",
"status":200,
"api":"1.1.0",
"count":128
},
"features":[
{
"type":"Feature",
"properties":{
"mag":2.07,
"place":"28km S of Gardnerville Ranchos, Nevada",
"time":1452460963440,
"updated":1452461071893,
"tz":-480,
"url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72578341",
"detail":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/nc72578341.geojson",
"felt":null,
"cdi":null,
"mmi":null,
"alert":null,
"status":"automatic",
"tsunami":0,
"sig":66,
"net":"nc",
"code":"72578341",
"ids":",nn00526227,nc72578341,",
"sources":",nn,nc,",
"types":",general-link,general-link,geoserve,nearby-cities,origin,phase-data,",
"nst":8,
"dmin":0.06765,
"rms":0.11,
"gap":197,
"magType":"md",
"type":"earthquake",
"title":"M 2.1 - 28km S of Gardnerville Ranchos, Nevada"
},
"geometry":{
"type":"Point",
"coordinates":[
-119.751503,
38.6351662,
-1.8
]
},
"id":"nc72578341"
},
{
"type":"Feature",
"properties":{
"mag":2.3,
In the extract above you have: "type" - JSON value, "metadata" - JSON Object, "features" - JSON Array and so on.
I recommend you looking into JSON syntax, so then you will be able to understand how to parse the data: http://www.w3schools.com/json/json_syntax.asp
Okay I am new to json and php so youll consider my question simple for you.
I am trying to insert data (name and id) from the app into the database .
and I got this error
org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
this is my php
<?php
$host='mysql12.000webhost.com';
$uname='a6901827_moudiz';
$pwd='**';
$db="a6901827_justed";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];
$sql = 'INSERT INTO samle '.
'(id ,name) '.
'VALUES ($id , $name )';
mysql_select_db('a6901827_justed');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
?>
and this is my code, if you think it needs improvement please don't hesitate.
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost =new HttpPost("http://justedhak.comlu.com/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
Based on the error, you are trying to pass HTML formatted text in JSON string.
If you expect to pass plain text, this means something is wrong with your PHP script which returns HTML (or it doesn't work as expected).
If you want to pass HTML-formatted text, you can encode your string before adding it to your JSON object.
You are sending data as:
http://justedhak.comlu.com/insert.php?id=x&name=myname
But expecting it to be
{"id": x, "name": "myname"}
which should be in the post body of the http call.
The easiest way would be to forget the JSON for now. Keep the Android code, and remove the JSON part from the PHP.
your reply does not contain JSON as well. So the exception fires at the Android code.
I'm working on a Android application and I'm trying to get a JSON response from a server which is configured to return a json object (".../current_user.json") when receives a GET message, but the answer I get is in HTML format and not in JSON format as expected.
I don't understand why is this happening because I did the same requests on the browser and with the program RESTClient and got the right answer in JSON format.
Here is the code I'm using.
JSONObject json = new JSONObject();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient httpClient = new DefaultHttpClient(params);
HttpGet get = new HttpGet(url_getiduser);
HttpResponse response = httpClient.execute(get);
String sresponse = "error";
Log.d("url get", url_getiduser);
Log.d("pedido get", get.getMethod());
if(response != null)
{
InputStream in = response.getEntity().getContent();
sresponse = convertStreamToString(in);
Log.d("resposta http", sresponse);
if(!sresponse.equals("error"))
{
JSONObject object = new JSONObject(sresponse);
id_user = (String) object.get("id");
json = object;
Log.d("objecto json", object.toString());
}
else Log.d("Error on json parser", sresponse);
There are few cases where you get HTML text
You might have called a wrong function which gives a 404 page.
Might be a database error on server side where you will get database error message
Server might be sending a styled data which has HTML tags
But you better Log the response and paste it here.
I'm parsing a json file but i get this message: org.json.JSONException: End of input at character 0 of
the contetnn of the file is:
Are you sure there is not an empty line at the end of the file? Like this:
[
{
code: "UNLC",
cours_jour: "40 020",
variation: "0.00"
},
{
code: "UNXC",
cours_jour: "7 450",
variation: "0.00"
}
]
<-- Empty line here!
Your JSON Object fields need to be encapsulated by quotes
IE
{
"code": "BOAC",
"cours_jour": "29 000",
"variation": "-1.69"
}
How was the JSON file generated?
--Edit
You can use the below code to download the page to a string and then convert it to a JSONArray and then pull each JSONObject. You cannot run any web requests on the main thread so either extend a new asynctask or thread or runnable to perform the below
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("http://www.impaxis-securities.com/securities/cours-actions/cours.json");
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response;
try {
response = httpclient.execute(httpost, responseHandler);
JSONArray arr = new JSONArray(response);
int arrLength = arr.length();
if(arrLength > 0)
{
for(int i = 0; i < arrLength; i++)
{
JSONObject item = arr.getJSONObject(i);
String code = item.getString("code");
String cours_jour = item.getString("cours_jour");
String variation = item.getString("variation");
//Either insert to a DB or add to an array list and return it
}
}
}
catch (ClientProtocolException e) {
//Issue with web server
}
catch (IOException e) {
//Issue with request
}
catch (JSONException e) {
//ISSUE Parsing JSON from site
}
---Edit
I tested the code and it looks like there is a bug with the JSON plugin/REST service
http://drupal.org/node/1433436
I try to use Twitter Get users/lookup to look up users information. But I got some error in parsing the response json file. The request URI is: "https://api.twitter.com/1/users/lookup.json?screen_name=nba". My code is:
public String getInternetData() throws Exception{
String data = null;
try {
URI website = new URI("https://api.twitter.com/1/users/lookup.json?screen_name=nba");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity);
try {
JSONObject jouser = new JSONObject(str);
data = jouser.getString("followers_count");
} catch (JSONException e) {
e.printStackTrace();
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection: " +e.toString());
}
return data;
}
The response JSON content is
[
{
"notifications":false,
"id":19923144,
"profile_link_color":"177BC7",
"profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1787324427\/National-Basketball-Association_normal.jpg",
"profile_background_image_url_https":"https:\/\/si0.twimg.com\/profile_background_images\/559347559\/12twitter_playoffs_0523.jpg",
"id_str":"19923144",
"following":false,
"profile_use_background_image":true,
"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1787324427\/National-Basketball-Association_normal.jpg",
"utc_offset":-18000,
"friends_count":988,
"profile_text_color":"333333",
"time_zone":"Eastern Time (US & Canada)",
"default_profile":false,
"followers_count":5095414,
"name":"NBA",
"profile_banner_url":"https:\/\/si0.twimg.com\/brand_banners\/NBA\/1335482314\/live",
"url":"http:\/\/www.nba.com",
"profile_sidebar_border_color":"eeeeee",
"created_at":"Mon Feb 02 19:04:42 +0000 2009",
"protected":false,
"listed_count":28499,
"profile_background_tile":false,
"contributors_enabled":true,
"profile_sidebar_fill_color":"ffffff",
"geo_enabled":false,
"description":"News and notes directly from the NBA.",
"location":"New York, NY",
"is_translator":false,
"show_all_inline_media":true,
"statuses_count":28818,
"follow_request_sent":false,
"lang":"en",
"profile_background_color":"000000",
"default_profile_image":false,
"verified":true,
"favourites_count":15,
"screen_name":"NBA",
"profile_background_image_url":"http:\/\/a0.twimg.com\/profile_background_images\/559347559\/12twitter_playoffs_0523.jpg"
}
]
Then I got the error: *Error parsing data: org.json.JSONException: Value [{"location"......
Anybody has an idea?
If the response starts with [ it means it is actually a JSON Array, not an object. Then, you will have to do something like this:
JSONArray array = new JSONArray(str);
JSONObject jsonObject = array.getJSONObject(0);
String followersCount = jsonObject.getString("followers_count");