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
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
I am having trouble figuring out why i'm getting a JSON exception while I am parsing my JSON object. I am getting(Http GET) the JASON from a URL. Here is all the relevant code, let me know if you need to see any more of the code
The doInBackground Async method:
#Override
protected Void doInBackground(Void... arg0)
{
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL,ServiceHandler.GET);
Log.w("Rakshak", "the jaon String is:"+jsonStr);// this prints the JASON in the log and it looks fine
// I am not pasting it in coz it is HUGE
if (jsonStr != null)
{
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.w("Rakshak", "in the try before the JASON");
// Getting JSON Array node
kingtide = jsonObj.getJSONArray("JASON");
// looping through All Kingtide events
for (int i = 0; i < kingtide.length(); i++)
{
JSONObject k = kingtide.getJSONObject(i);
String date = "Date Range:"+k.getString(KEY_DATE);
String lat = k.getString(KEY_LAT);
String lng = k.getString(KEY_LNG);
String loc = "Location of the Kingtide:"+k.getString(KEY_LOC)+", "+k.getString(KEY_STATE);
String temp_Time = k.getString(KEY_TIME);
String[] time_parts = temp_Time.split("T");
String time = "Kingtide at:"+time_parts[1]+" "+getYear(time_parts[0]);
// tmp hashmap for single kingtide event
HashMap<String, String> kt = new HashMap<String, String>();
// adding each child node to HashMap key => value
kt.put(KEY_DATE, date);
kt.put(KEY_LAT, lat);
kt.put(KEY_LNG, lng);
kt.put(KEY_LOC, loc);
kt.put(KEY_TIME, time);
Log.w("Rakshak", KEY_DATE+KEY_LAT+KEY_LNG+KEY_LOC+KEY_TIME);
// adding the kingtide to the kingtide hash map. this will be used to fill up the list view
kingTideList.add(kt);
}
} catch (JSONException e) {
Log.e("Rakshak", "JSONException "+e.getMessage()); // this prints "JSONException Value [{"Latitude":-19.9078861,"Location":"Abbot....." and the rest of the JASON(all of it)
}
}
else
Log.w("Rakshak", "JASON string is null");
return null;
}
the Service handler class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.e("Rakshak", "UnsupportedEncodingException "+e.getMessage());
} catch (ClientProtocolException e) {
Log.e("Rakshak", "ClientProtocolException "+e.getMessage());
} catch (IOException e) {
Log.e("Rakshak", "IOException "+e.getMessage());
}
Log.w("Rakshak", "In the service handeler: this is a test");
return response;
}
}
Part of the stacktrace:
03-14 10:09:56.861: E/Rakshak(7037): JSONException Value [{"Latitude":-19.9078861,"Location":"Abbot Point","Longitude":148.08467259999998,"DateRange":"1–3 January 2014","HighTideOccurs":"2014-01-02T09:47:00","State":"QLD"},{"Latitude":-27.477819,"Location":"Brisbane
The URL for the JASON file is "http://witnesskingtides.azurewebsites.net/api/kingtides"
NOTE: I know it looks like a XML file but it is JASON . Just run it through a validator/viewer and see for your self if you want.
My question in why am I getting a JASON exception and how do I fix it.
The Response you are getting is XML response and you are trying to parse it as JSON.
Refer this tutorial on XML parsing
When getting the contents, I get this back (part of it):
[
{
"Location": "Abbot Point",
"State": "QLD",
"HighTideOccurs": "2014-01-02T09:47:00",
"DateRange": "1–3 January 2014",
"Latitude": -19.9078861,
"Longitude": 148.08467259999998
},
{
"Location": "Brisbane Bar",
"State": "QLD",
"HighTideOccurs": "2014-01-02T10:16:00",
"DateRange": "1–3 January 2014",
"Latitude": -27.477819,
"Longitude": 153.01889119999998
},
...
]
This means that your object is already an array. Try to change this in your code:
//JSONObject jsonObj = new JSONObject(jsonStr);
Log.w("Rakshak", "in the try before the JASON");
// Getting JSON Array node
kingtide = new JSONArray(jsonStr);
since the returned jsonStr is already an array (and not an object with an array-attribute called "JASON").
Confirmed that the service is in fact returning a JSON response (you can check this in a tool like Fiddler). The default response from the API is JSON. The reason you are seeing XML by clicking the link provided in the question is because the browser is requesting a content type of application/xml, so that is what the browser shall receive.
I don't know the answer to your actual problem though, as the JSON seems to validate in everything I've tried. Maybe an incompatibility with the Android parser?
I'd suggest trying a different parser in your Android app to parse the response from the server. I've used Gson before which was easy to set up and use.
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
The service returns an array of objects so instead of
JSONObject jsonObj = new JSONObject(jsonStr);
use
JSONArray jsonArray = new JSONArray(jsonStr);
and continue from there.
Update: Disregard my answer below...
Not to burst your repeated notion of the fact that it is JSON, it is not.
The response that your code gets back is plain XML.
However,
The resource you are requesting ( http://witnesskingtides.azurewebsites.net/api/kingtides ) supports both XML formatted responses and JSON formatted responses. It probably all has to do with the Accept headers that are missing from your request in your code or are set to application/xml or text/xml or something similar in your ServiceHandler.
When your code gets the response of the server, the server does not find an Accept header and returns XML format.
When the JSON validator sites, that you mention, request the same URL, they likely add an Accept header that tells the server to return the response in JSON format.
I'm not sure how the ServiceHandler class works, but when you create a GET request you should add the HTTP Header with name Accept and value application/json and then issue the request. You now will get JSON back instead of XML.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
In the below code I am trying to populate the JSON array with JSON objects (book, and camera).
[ {
"camera":{
"picture":"http:\/\/img7.flixcart.com\/image\-imacyb5emj5yztet.jpeg",
"model":"Lumix DMC-FP3 Point & Shoot",
"make":"Panasonic",
"price":5830
}
},
{
"camera":{
"picture":"http:\/\/sp.sony-europe.com\/da.jpeg",
"model":"Digital Still Camera - H Series - DSC-HX200V",
"make":"Sony",
"price":510
}
},
{
"book":{
"description":"What is self, and how can a",
"authors":"Douglas R Hofstadter",
"price":650,
"id":40724766,
"title":"G\u00f6del, Escher, Bach: an Eternal Golden Braid"
}
},
{
"camera":{
"picture":"http:\/\/www.usa.canon.com\/60d_586x186.gif",
"model":"Digital SLR Camera EOS 60D",
"make":"Canon",
"price":999
}
},
{
"book":{
"description":"Tgdfgf fgfg ",
"authors":"Harold Abelson and Gerald Jay Sussman with Julie Sussman",
"price":469,
"id":51087,
"title":"Structure and Interpretation of Computer Programs"
}
},
]
public void getDetalFromServer() {
// TODO Auto-generated method stub
String URL="xyz.php";
HttpClient client= new DefaultHttpClient();
HttpPost post=new HttpPost(URL);
try {
HttpResponse response =client.execute(post);
HttpEntity getResEntity=response.getEntity();
String result="";
if(getResEntity!=null){
result=EntityUtils.toString(getResEntity);
System.out.println("result from server: "+result);
bookDescription=new ArrayList<String>();
bookAuthors=new ArrayList<String>();
bookPrice=new ArrayList<String>();
bookID=new ArrayList<String>();
bookTitle=new ArrayList<String>();
responseArray=new JSONArray(result);
for(int i=0;i<responseArray.length();i++){
JSONObject bookObject=(JSONObject) responseArray.getJSONObject(i);
bookDescription.add(bookObject.get("description").toString());
bookAuthors.add(bookObject.get("authors").toString()); bookPrice.add(bookObject.get("price").toString());
bookID.add(bookObject.get("id").toString()); bookTitle.add(bookObject.get("title").toString());
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
Using this code I am able to just get the first object of the response. Now I am just trying to parse Music object from the response.
responseArray=new JSONArray(result);
JSONObject bookObject=null;
JSONObject json_user1=null;
JSONObject json_user2=null;
for(int i=0;i<responseArray.length();i++){
bookObject= responseArray.getJSONObject(i);
if (bookObject.has("book")){
json_user1 = bookObject.getJSONObject("book");
bookDescription.add(json_user1.getString("description").toString());
bookAuthors.add(json_user1.getString("authors").toString());
}
else if(bookObject.has("camera")){
json_user2 = bookObject.getJSONObject("camera");
/** Add Camera data in the lists here same as done for book */
}
}
Try this.... Inside your json array you have put json objects. so you need to retrieve json objects like book and camera from the array first and then from book object you can get the description and all... :)
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");
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();
}