Trying to convert JSON data to a JSON array in Android Studio - android

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

Related

How to make JSONarray of object using MultipartEntity?

I have to post such json using MultipartEntity.
{
arrayName":[
{
// object one
},
{
// object two
}]
}
I don't get an idea how to make such structure once posting multipartEntity object, what i have tried so far is.
MultipartEntity entity = new MultipartEntity();
entity.addPart("key","value");
.....
.....
..... all keys
httppost.setEntity(entity);
Is there any way so i can make MultipartEntity array or what?
NOTE: for separate posting one json object it work very fine. I just want to learn how to create JSONarry format, once posting with MultipartEntity.
You have to convert your json array to string.
Use Gson Library for that. Gson
Now you just have to use like this.
Whatever you model is so
ArrayList<CustomClass> objects = new ArrayList<>();
objects.add(object);
objects.add(object);
and then just use gson.
String stringToPost = new Gson().toJson(objects);
then add multipart this string as
Stringbody
Server side will deserialize String to Json Array.
Also you can add file as filebody in multipart.
This is an example to upload image and JSONArray using MultipartEntity-- lib:org.apache.http.entity.mime
List students = getStudentList();
MultipartEntity studentList = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i=0; i<students.size();i++){
try {
studentList.addPart("studentList[][name]", new StringBody(String.valueOf(students.get(i).getName())));
studentList.addPart("studentList[][addmission_no]", new StringBody(String.valueOf(students.get(i).getAddmissionNo)));
studentList.addPart("studentList[][gender]", new StringBody(String.valueOf(students.get(i).getGender)));
File photoImg = new File(students.get(i).getImagePath());
studentList.addPart("studentList[][photo]",new FileBody(photoImg,"image/jpeg"));
}catch(Exception e){
e.getMessage();
}
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.addHeader("X-Auth-Token", mUserToken);
post.setEntity(studentList);
org.apache.http.HttpResponse response = null;
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = response.getEntity();
JSONObject myObject;
try {
String result = EntityUtils.toString(httpEntity);
// do your work
} catch (IOException e) {
e.printStackTrace();
}

Downloading a JSON Array from a URL in Android

I'm trying to download a JSON file in this format
[
{
"CRN":"10001",
"Course":"REG1"
},
{
"CRN":"10002",
"Course":"REG2"
}
]
I understand how to use a JSONArray class once it is created but I don't know how to create the JSONArray object from the file. If the URL location of the file were to be "www.test.com" how would I go about downloading it in background upon the launch of my application so as to not interfere with the launching of the app but not require the user to manually download it themselves.
You might want to check out this helpful library: Retrofit
It makes grabbing and parsing JSON data easy!
I think you should look for Android Web Service example. Where you can find info about
1.How to make a HTTP request to server (using URL eg. www.google.com)
2. How to handle Response from Server
3. How to parse JSON/XML response from Server etc.
Here is the Simple Tutorial I Found for you.
Android Web service for Log-in and Registration
Just go through step by step.
In the example we are making request to server for login and getting response then going ahead in app.
Here is the code snipp.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
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");
}
is.close();
json = sb.toString();
Log.e("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 " + e.toString());
}
// return JSON String
return jObj;
}
}
A good way to download the JSON file automatically, would be to launch an AsyncTask during your onCreate method of the home activity.
JSON files are nothing more than text files in a special format, so the could be easily downloaded as a response from a HttpURLConnection, and then be treated as a String.
A suggestion for parsing the JSON objets into Java objects would be the Jackson JSON Processor. You could use the class ObjectMapper of this library to automatically create the objects.
If you are planing to implement the server side by yourself, and you also need a library to send JSON objects, you could use Jersey on both server and client.

JsonArray parsing

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

Error parsing twitter json response in android

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

Json parsing problem android

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

Categories

Resources