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");
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
So I am trying to post to a rails app from an Android app I am writing. I am able to post successful from inside the rails app. I was also able to post successfully using a chrome add on called Simple Rest client.
When I try and post from the Android app its hitting the rails app but creating an empty post. None of the input data is being received by rails.
I read that 3rd party applications are only able to GET from a Rails app depending on authentication so to make sure this wasn't the issue I was having I added this to my Rails config.
# de-activate tolken auth
config.action_controller.allow_forgery_protection = false
At this point I am unsure as to where my issue lies, with my Rails backend or my Android client.
ok so the Rails post method in my controller that I'm trying to reach is here
# POST /orders
# POST /orders.json
def create
#order = Order.new(params[:order])
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render json: #order, status: :created, location: #order }
else
format.html { render action: "new" }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
Here is the Android java code for sending the Post Request.
This is the method passing in the User input data I am trying to POST
private void postInformationtoAPI() {
showToast("POSTING ORDER");
List<NameValuePair> apiParams = new ArrayList<NameValuePair>();
apiParams.add(new BasicNameValuePair("drinks_id", GlobalDrinkSelected));
apiParams.add(new BasicNameValuePair("name", GlobalEditTextInputName));
apiParams.add(new BasicNameValuePair("paid" , GlobalIsPaid));
bgtPost = new BackGroundTaskPost(MAP_API_URL_POST_ORDER, "POST", apiParams);
bgtPost.execute();
goToOrderCompleted();
}
And this is the class that it is passed to, permorming the HTTP POST.
public class BackGroundTaskPost extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
String URL = null;
String method = null;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public BackGroundTaskPost(String url, String method, List<NameValuePair> params) {
this.URL = url;
this.postparams = params;
this.method = method;
for (int i = 0; i < postparams.size(); i++){
String test = postparams.get(i).toString();
Log.d("This is in the lisht:", test);
}
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// 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(postparams, HTTP.UTF_8));
Log.i("postparams : ", postparams.toString());
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils
.format(postparams, "utf-8");
URL += "?" + paramString;
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 {
Log.i("Logging out *is* before beffered reader", is.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
Log.i("Logging out *is* after beffered reader", is.toString());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("json: ",json);
} 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 TEST " + e.toString());
}
// return JSON String
return jObj;
}
}
This is the what log's out for postparams in the above class, so I know data is actually being sent
04-03 21:36:23.994: I/postparams :(690): [drinks_id=41, name=Dave, paid=True]
This is what Log Cat is showing as a response from the server
04-03 20:56:08.247: I/json:(690): {"created_at":"2013-04-03T20:56:06Z","drinks_id":null,"id":1351,"name":null,"paid":null,"served":null,"updated_at":"2013-04-03T20:56:06Z"}
I am really struggling to understand where the issue lies with this and have been stuck on it for quite awhile. Any insight would be much appreciated. And if any more information is needed just shout.
Edit: logs from server
This is a successful post from the simple REST client
2013-04-03T23:13:31+00:00 app[web.1]: Completed 200 OK in 15ms (Views: 8.7ms | ActiveRecord: 5.2ms)
2013-04-03T23:13:42+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 23:13:42 +0000
2013-04-03T23:13:42+00:00 app[web.1]: Processing by OrdersController#create as JSON
2013-04-03T23:13:42+00:00 app[web.1]: Parameters: {"updated_at"=>nil, "drinks_id"=>51, "id"=>1021, "name"=>"Test", "paid"=>true, "served"=>nil, "created_at"=>nil, "order"=>{"drinks_id"=>51, "name"=>"Test", "paid"=>true, "served"=>nil}}
2013-04-03T23:13:43+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=1ms service=25ms status=201 bytes=138
2013-04-03T23:13:43+00:00 app[web.1]: Completed 201 Created in 15ms (Views: 0.6ms | ActiveRecord: 13.2ms)
This is from the android app posting
2013-04-03T22:56:45+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 22:56:45 +0000
2013-04-03T22:56:45+00:00 app[web.1]: Processing by OrdersController#create as JSON
2013-04-03T22:56:45+00:00 app[web.1]: Completed 201 Created in 23ms (Views: 2.2ms | ActiveRecord: 16.3ms)
2013-04-03T22:56:45+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=4ms service=37ms status=201 bytes=138
You're setting a content-type of JSON but not actually sending JSON, you're sending standard POST url-encoded parameters.
You need to actually send a JSON object:
JSONObject params = new JSONObject();
params.put("drinks_id", GlobalDrinkSelected);
params.put("name", GlobalEditTextInputName);
params.put("paid", GlobalIsPaid);
StringEntity entity = new StringEntity(params.toString());
httpPost.setEntity(entity);
The problem is that when you're building the POST in Android you're over-writing the entity (the body). You initially set it and then you set it again, effectively clearing out what you already set.
This is correct:
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
But then a couple of lines later you over-write it with:
httpPost.setEntity(new StringEntity("UTF-8"));
So ditch that 2nd setEntity() call.
You can achieve what you're trying to do - setting the POST body in UTF-8 by tweaking your code like:
httpPost.setEntity(new UrlEncodedFormEntity(postparams, HTTP.UTF_8));
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
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();
}