Extracting JSONObject fromJSONArray - java

working on an android application to try and connect to "steemit.com' and return JSON data to me.
Everything has been working so far, printing the mass response from the URL to the Textview, only I am now getting no errors, and no text printed out in the screen so I assume I am using the wrong type of object or something. Perhaps the data I am trying to retrieve is not an Array? What do you all think? Here is my code.
public class fetchdata extends AsyncTask<Void,Void,Void> {
String data = "";
String dataParsed = "";
String singleParsed = "";
#Override
protected Void doInBackground(Void... voids) {
{
try {
URL url = new URL("https://steemit.com/#curie.json");
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
InputStream inputStream = httpsURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String lines = "";
while(lines != null){
lines = bufferedReader.readLine();
data = data + lines;
}
JSONArray JA = new JSONArray(data);
for (int i =0 ;i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "User: " + JO.get("user") + "\n" +
"Location: " + JO.get("location") + "\n" +
"ID: " + JO.get("id")+"\n";
dataParsed = dataParsed + singleParsed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
followers.dataTV.setText(this.dataParsed);
}
}
and the page I expect the TextView to display data on.
public class followers extends AppCompatActivity {
public static TextView dataTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followers);
ListView followList = (ListView)findViewById(R.id.followList);
dataTV = (TextView)findViewById(R.id.followersTVData);
fetchdata process = new fetchdata();
process.execute();
}
}
If I have not been clear, what the issue is, is that when I 'printText' using the variable 'data', there is no problems, and the bulk text is printed, however, I am now trying to break it down into bits, and it is just not printing anything when I use the variable 'dataParsed'. Any help is appreciated. Thank you in advance!
I have been asked for the response. Here it is, though rather long.
{"user":{"id":1026971,"name":"ceruleanblue","owner":{"weight_threshold":1,"account_auths":[],"key_auths":[["STM7UPr1LJMw4aAxcuiYAmad6bjjiaeDcfgSynRMrr5L6uvuSJLDJ",1]]},"active":{"weight_threshold":1,"account_auths":[],"key_auths":[["STM7qUaQCghsFZA37fTxVB4BqBBK49z35ni6pha1Kr4q4qLkrNRyH",1]]},"posting":{"weight_threshold":1,"account_auths":[["minnowbooster",1],["steemauto",1]],"key_auths":[["STM7qF27DSYNYjRu5Jayxxxpt1rtEoJLH6c1ekMwNpcDmGfsvko6z",1]]},"memo_key":"STM7wNQdNS9oPbVXscbzn7vfzjB7SwmLGQuFQNzZgatgpqvdKzWQZ","json_metadata":{"profile":{"profile_image":"https://cdn.steemitimages.com/DQmfNj7SLU1aBtV9UkJa5ZKMZPNuzR4ei5UJRA54JxFk99M/Mushrooms%20Trippy%20Art%20Fabric%20Cloth%20Rolled%20Wall%20Poster%20Print.jpg","name":"Cerulean's Chillzone","about":"IT Technician, Programmer, Day Trader, Night Toker.","location":"Ontario, Canada","cover_image":"https://cdn.steemitimages.com/DQmTwT379V7EcQ1ZkqkmJkpWyu4QXw1LzDinv9uoyixksMY/tumblr_static_tumblr_static__640.jpg"}},"proxy":"","last_owner_update":"2018-06-18T19:57:39","last_account_update":"2018-08-01T04:33:06","created":"2018-06-03T20:28:21","mined":false,"recovery_account":"steem","last_account_recovery":"1970-01-01T00:00:00","reset_account":"null","comment_count":0,"lifetime_vote_count":0,"post_count":321,"can_vote":true,"voting_power":9800,"last_vote_time":"2018-08-09T02:47:03","balance":"8.000 STEEM","savings_balance":"0.000 STEEM","sbd_balance":"1.979 SBD","sbd_seconds":"927621285","sbd_seconds_last_update":"2018-08-09T13:23:15","sbd_last_interest_payment":"2018-07-11T10:18:12","savings_sbd_balance":"0.000 SBD","savings_sbd_seconds":"2067163545","savings_sbd_seconds_last_update":"2018-07-23T08:58:48","savings_sbd_last_interest_payment":"2018-07-09T06:32:27","savings_withdraw_requests":0,"reward_sbd_balance":"0.000 SBD","reward_steem_balance":"0.000 STEEM","reward_vesting_balance":"0.000000 VESTS","reward_vesting_steem":"0.000 STEEM","vesting_shares":"167703.513691 VESTS","delegated_vesting_shares":"29412.000000 VESTS","received_vesting_shares":"0.000000 VESTS","vesting_withdraw_rate":"0.000000 VESTS","next_vesting_withdrawal":"1969-12-31T23:59:59","withdrawn":0,"to_withdraw":0,"withdraw_routes":0,"curation_rewards":182,"posting_rewards":110408,"proxied_vsf_votes":[0,0,0,0],"witnesses_voted_for":1,"last_post":"2018-08-07T12:43:42","last_root_post":"2018-08-07T12:25:39","average_bandwidth":"44620566375","lifetime_bandwidth":"1099256000000","last_bandwidth_update":"2018-08-09T13:23:15","average_market_bandwidth":3415484305,"lifetime_market_bandwidth":"237250000000","last_market_bandwidth_update":"2018-08-07T13:21:39","vesting_balance":"0.000 STEEM","reputation":"1564749115439","transfer_history":[],"market_history":[],"post_history":[],"vote_history":[],"other_history":[],"witness_votes":["guiltyparties"],"tags_usage":[],"guest_bloggers":[]},"status":"200"}null
Perhaps I have implemented this improperly?
for (int i =0 ;i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.getJSONObject(i);
singleParsed = "User: " + JO.get("user.id") + "\n" +
"Location: " + JO.get("location") + "\n" +
"ID: " + JO.get("id")+"\n";
dataParsed = dataParsed + singleParsed;
}
UPDATED FIXES, STILL BROKEN BUT FARTHER ALONG.
String lines = "";
while(lines != null){
lines = bufferedReader.readLine();
data = data + lines;
}
JSONObject JO = new JSONObject(data);
String m = "";
for (int i =0 ;i < JO.length(); i++){
// JSONObject JO = (JSONObject) JO.getJSONObject(i);
singleParsed = "User: " + JO.getString("user.id") + "\n" +
"Location: " + JO.getString("location") + "\n" +
"ID: " + JO.getString("id")+"\n";
dataParsed = dataParsed + singleParsed;
DEBUGGER BREAKS ON "singleParsed = "user:", any ideas from here?

The response is a JSONObject not a JSONArray.
So, you can directly use: new JSONObject(data); in your code.
Also, as you haven't noticed, there's a null at the end after the closing brace.

I think you should parse the data with JSONObject, because the response is not an array. You should create class which contain User class and String for the status to handle the response.
Or you can use retrofit instead.
http://square.github.io/retrofit/

Try this...
try {
JSONObject object = new JSONObject(data);
String user = object.getString("user");
int id = user.getInt("id");
String name = user.getString("name");
String owner = user.getString("owner");
int weight_threshold = owner.getInt("weight_threshold");
JSONArray account_auths = owner.getJSONArray("account_auths");
.....
} catch (Exception e) {
e.printStackTrace();
}
pass other objects so on.

Related

Yelp API search request with iteration - How to make the iteration

Below I have my code for a search request. As yelp only allows to get only 50 results I have a problem to make it work.
So basically offset = 0 and limit = 50 will bring me the results 0-50
offset = 50 and limit = 50 will bring me the results 51-100
So and in my case I need 1000 Results. How can I manage it? I tried everything in my power and now I need some help.
public class Search2 {
static HttpURLConnection conn;
public static void Searche() {
int offset = 0;
int limit = 50;
try {
for (int i = 0; i < 950; i=+50) {
URL url = new URL("https://api.yelp.com/v3/businesses/search?location=" + gui.Lead_1.tFOrt.getText()
+ "&categories=" + gui.Lead_1.tFKeyword.getText() + "&offset=" + i + "&limit=50");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
}
try {
conn.setRequestProperty("Authorization", "Bearer " + dbb.Pfad.getPath() + " ");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// throwing the error message if the response is not available.
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
// capturing the response and appending it to the response string.
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
StringBuffer response = new StringBuffer();
while ((output = br.readLine()) != null) {
response.append(output);
}
// converting the response to the JSONObject.
JSONObject jsonObj = new JSONObject(response.toString());
JSONArray list1 = new JSONArray();
JSONArray arr = jsonObj.getJSONArray("businesses");
JSONObject details = new JSONObject();
// capturing the specific values(name, rating, reviewcount) from the response
for (int i = 0; i < arr.length(); i++) {
String name = arr.getJSONObject(i).getString("name");
int rating = arr.getJSONObject(i).getInt("rating");
int review_count = arr.getJSONObject(i).getInt("review_count");
JSONObject address = arr.getJSONObject(i).getJSONObject("location");
details.put("Name", name);
details.put("Rating", rating);
details.put("Review Count", review_count);
details.put("Address", address);
JSONObject object = new JSONObject();
object.put("restaurant " + (i + 1), details);
list1.put(object);
Lead_2.row[0]=i+1;
Lead_2.row[1]=arr.getJSONObject(i).getString("name");
Lead_2.row[2]=arr.getJSONObject(i).getJSONObject("location").getString("address1");
Lead_2.model.addRow(Lead_2.row);
}

Showing data when multiple objects exist in JSON URL

I have a JSON File, showing the following:
{
"version": 2,
"locations": [{
"id": "750",
"geo": {
"name": "Lord Howe Island",
"state": "Lord Howe Island",
"country": {
"id": "au",
"name": "Australia"
},
"latitude": -31.557,
"longitude": 159.086
},
"astronomy": {
"objects": [{
"name": "moon",
"days": [{
"date": "2018-09-05",
"events": [],
"moonphase": "waningcrescent"
}]
}]
}
}]
}
I am attempting to show in a TextView the following fields:
name "Lord Howe Island"
latitude "-31.557"
longitude "159.086"
moonphase "waningcrescent"
I have tried the following:
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Name:" + JO.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + JO.get("moonphase") + "\n";
}
But unfortunately I do not receive any results.
What am I doing wrong? Thanks very much for any help.
Edit - Full Code for assistance.
public class fetchData extends AsyncTask<Void, Void, Void> {
String data = "";
String dataParsed = "";
String singleParsed = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("example.com"); //Replace with API URL
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
JSONObject geo = JO.getJSONObject("geo");
JSONObject astronomy = JO.getJSONObject("astronomy");
singleParsed = "Name:" + geo.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + astronomy.get("moonphase") + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.fetcheddata.setText(this.data);
}
}
Try this
JSONObject data=new JSONObject(data);
JSONArray JA = data.getJSONArray("locations");
for (int i = 0; i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
JSONObject geo=JO.getJSONObject("geo");
JSONObject astronomy=JO.getJSONObject("astronomy");
singleParsed = "Name:" + geo.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + astronomy.get("moonphase") + "\n";
instead of parsing JSON on your own use gson
Gson gson= new Gson();
YourBeanClass yourBeanClass gson.fromJson(jsonString,YourBeanClass.class)
Json to Java POJO
From above you can get as Bean class just use it to parse your Json.Using POJO to parse json is easy and less vulnerable to error/exception.
For your Json i tried getting the bean object and tried parsing.
And your code will also be more readable:
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("example.com"); //Replace with API URL
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
Gson gson= new Gson();
YourBeanClass yourBeanClass gson.fromJson(jsonString,YourBeanClass.class)
//get and set all your data here from your bean
String country=yourBeanClass.getCountry()
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Your json parsing is wrong.First of all there is just one object in your json array there is no need of the for loop. You can access it directly using 0th index.
Second
JSONObject JO = (JSONObject) JA.get(i);
This line just gave you the 1st json object inside the array. You have to do one more step to fetch the name.
JSONObject geo=JO.getJSONObject("geo");
Now fetch the name from geo object.
"Name:" + geo.getString("name") + "\n"
Also remember your moonphase string is part of different array. So you need to parse that accordingly
You have to get value of the type defined in your json.For eg. for getting string type it will be
jsonObject.getString("key");
for integer it will be
jsonObject.getInt("key")

Parsing JSON string in Java android

I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.
"place": [
{
"address": {
"country_code": "fr",
"country": "France",
"state": "Normandie",
"county": "Calvados"
},
"icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
"importance": 0.74963706049207,
"type": "administrative",
"class": "boundary",
"display_name": "Calvados, Normandie, France",
"lon": "-0.24139500722798",
"lat": "49.09076485",
"boundingbox": [
"48.7516623",
"49.4298653",
"-1.1597713",
"0.4466332"
],
"osm_id": "7453",
"osm_type": "relation",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
"place_id": "158910871"
}
]
any help would be appreciated. thanks.
these is my android code :
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
Log.e("mylog",adresse);
}
In your JSON string, "place" is a JSONArray and its containing another JSONObject. Get "place" value as below:
// Place
JSONArray place = jsonObj.getJSONArray("place");
Get "address" value as below:
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
Get "countryCode", "country", "state" and "county" value as below:
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Here is the fully working code. Try this:
public void parseJson() {
// Your JOSON string
String jsonStr = "{\"place\": [\n" +
" {\n" +
" \"address\": {\n" +
" \"country_code\": \"fr\",\n" +
" \"country\": \"France\",\n" +
" \"state\": \"Normandie\",\n" +
" \"county\": \"Calvados\"\n" +
" },\n" +
" \"icon\": \"http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png\",\n" +
" \"importance\": 0.74963706049207,\n" +
" \"type\": \"administrative\",\n" +
" \"class\": \"boundary\",\n" +
" \"display_name\": \"Calvados, Normandie, France\",\n" +
" \"lon\": \"-0.24139500722798\",\n" +
" \"lat\": \"49.09076485\",\n" +
" \"boundingbox\": [\n" +
" \"48.7516623\",\n" +
" \"49.4298653\",\n" +
" \"-1.1597713\",\n" +
" \"0.4466332\"\n" +
" ],\n" +
" \"osm_id\": \"7453\",\n" +
" \"osm_type\": \"relation\",\n" +
" \"licence\": \"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\n" +
" \"place_id\": \"158910871\"\n" +
" }\n" +
" ]}";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Place
JSONArray place = jsonObj.getJSONArray("place");
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Log.d("SUCCESS", "State: " + state + " Country: " + country + " County: " + county);
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
}
Hope this will help~
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.
Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.
Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.
Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.
For more details you can check this JSON Parsing in Android post.
Change for this:
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
JSONArray placeArray = object3.getJSONArray("place")
JSONObject addressObject = placeArray.getJSONObject("address");
adress = addressObject.getString("state");
Log.e("mylog",adresse);
}
If your initial part of the JSON Parsing code is correct, then this should work!
JSONArray jArray = new JSONArray(result);
JSONObject objectPremium = jArray.get(0);
JSONObject json = jsonObject.getJSONObject("address");
String state = json.getString("state");
String country = json.getString("country");
Check this code,
this is how you parse and store in a list
String jsonStr = //your json string
HashMap<String, String> addressList= new HashMap<>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray address = jsonObj.getJSONArray("address"); // for the address
// looping through All that
for (int i = 0; i < address.length(); i++) {
JSONObject c = address.getJSONObject(i);
String country_code= c.getString("country_code");
String country= c.getString("country");
String state= c.getString("state");
String county = c.getString("county");
// adding each child node to HashMap key => value
address.put("country_code", country_code);
address.put("country", country);
address.put("state", state);
address.put("county", county);
// adding address to address list
addressList.add(address);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}

How to parse a multi-array JSON (Java)

I'm currently working on a project that requires the latitude and longitude of a given address (input). Google maps API returns in json format, and I've done research and found that json-simple is the best option for my project. I have this code as well as the String output from google maps API, and would highly appreciate some help in parsing properly.
Also note: the call: MapTile.receiveJson just returns the string from google's API (linked below)
try {
String jsonAdr = MapTile.receiveJson("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonAdr);
System.out.println("lat=" + json.get("address_components"));
} catch (Exception e1) {e1.printStackTrace();System.out.println("Error contacting google or invalid input");}
This is the exact string output from google's API:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
I realize I could do String parsing, however it would be inefficient as I will be using more of google's API. I have also viewed other stack overflow, as well as their JSON website but found no examples with multiple JSON arrays such as those returned by google.
Any help is greatly appreciated.
Here's the solution:
I basically made a stand alone and I parsed your JSON like this:
First : This is the method I used to parse the JSON:
public String loadJSON(String someURL) {
String json = null;
HttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(someURL);
try {
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
StatusLine statusline = mHttpResponse.getStatusLine();
int statusCode = statusline.getStatusCode();
if (statusCode != 200) {
return null;
}
InputStream jsonStream = mHttpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
json = builder.toString();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
mHttpClient.getConnectionManager().shutdown();
return json;
}
Second : Used Async Task to download the data:
public class BackTask extends AsyncTask<Void, Void, Void> {
String url;
public BackTask(String URL) {
super();
this.url = URL;
}
#Override
protected Void doInBackground(Void... params) {
getData(url);
return null;
}
}
Third: Method to get the data and parse it. I have made some comments for this part since it's a bit long than usual.
public void getData(String URL) {
try {
JSONObject mainJsonObject = new JSONObject(loadJSON(URL));
// Log.d("JSON Data : ", mainJsonObject.toString());
String Status = mainJsonObject.getString("status");
Log.d("JSON Status : ", Status + "\n" + "---------------------");
JSONArray mainArray = mainJsonObject.getJSONArray("results");
// Log.d("JSON Array : ", mainArray.toString());
for (int i = 0; i < mainArray.length(); i++) {
JSONObject insideJsonObject = mainArray.getJSONObject(i);
if (insideJsonObject != null) {
String address_components = insideJsonObject
.getString("address_components");
// Log.d("Inside JSON Array : ", address_components);
JSONArray addressJSON = insideJsonObject
.getJSONArray("address_components");
// Log.d("Inside JSON ADDress : ", addressJSON.toString());
String formatted_address = insideJsonObject
.getString("formatted_address");
Log.d("Inside JSON formatted_address : ", formatted_address
+ "\n" + "-----------");
for (int ji = 0; ji < mainArray.length(); ji++) {
JSONObject geoMetryJO = mainArray.getJSONObject(ji);
if (geoMetryJO != null) {
JSONObject geometry = geoMetryJO
.getJSONObject("geometry");
// Log.d("Inside JSON geometry : ",
// geometry.toString()+"\n"+"----------");
String location_type = geometry
.getString("location_type");
Log.d("Inside JSON location_type : ", location_type
+ "\n" + "------------");
JSONObject locationJSONObject = geometry
.getJSONObject("location");
String Latitude = locationJSONObject
.getString("lat");
Log.d("Inside JSON Latitude : ", Latitude + "\n"
+ "--------------");
String Longitude = locationJSONObject
.getString("lng");
Log.d("Inside JSON Longitude : ", Longitude + "\n"
+ "------------");
JSONObject viewportJSONObject = geometry
.getJSONObject("viewport");
// Log.d("Inside JSON viewportJSONObject : ",
// viewportJSONObject.toString()+"\n"+"------------");
JSONObject northeastJSONObject = viewportJSONObject
.getJSONObject("northeast");
String Lat = northeastJSONObject.getString("lat");
Log.d("Inside JSON Lat : ", Lat + "\n"
+ "------------");
String Lon = northeastJSONObject.getString("lng");
Log.d("Inside JSON Lon : ", Lon + "\n"
+ "------------");
JSONObject southwestJSONObject = viewportJSONObject
.getJSONObject("southwest");
String south_Lat = southwestJSONObject
.getString("lat");
Log.d("Inside JSON south_Lat : ", south_Lat + "\n"
+ "------------");
String south_Lon = southwestJSONObject
.getString("lng");
Log.d("Inside JSON south_Lon : ", south_Lon + "\n"
+ "------------");
}
}
for (int k = 0; k < addressJSON.length(); k++) {
JSONObject addressJSONObject = addressJSON
.getJSONObject(k);
if (addressJSONObject != null) {
String long_name = addressJSONObject
.getString("long_name");
Log.d("Inside JSON LongName : ", long_name);
String short_name = addressJSONObject
.getString("short_name");
Log.d("Inside JSON ShortName : ", short_name);
JSONArray addressJSONArray = addressJSONObject
.getJSONArray("types");
Log.d("Inside JSON JSONADD : ",
addressJSONArray.toString() + "\n"
+ "-------------");
}
}
JSONArray insideJsonArray = insideJsonObject
.getJSONArray("types");
Log.d("Inside JSON Types : ", insideJsonArray.toString());
String street = insideJsonObject.getString("types");
Log.d("Inside JSON Street : ", street);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
After getting all the data, you can use it in anyway you want cause it's mostly in the string format. You can just copy and paste this method and it should run fine.
Fourth : On the onCreate() method, just executed the task like this:
public static final String URL = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackTask(URL).execute();
}
This was the complete solution for this question. Let me know if have any questions for this. Hope this helps..Good Luck.. :)
I did this for formatted_address. I type casted explicitly here. But getJSONArray () and getJSONObject() methods will perform the typecasting too.
// parse the Result String to JSON
JSONObject myJSONResult = new JSONObject(results);
for (int i = 0; i <((JSONArray) myJSONResult.get("results")).length(); i++)
System.out.println(((JSONObject) ((JSONArray) myJSONResult.get("results")).get(i)).get("formatted_address")); // This is your final options.

How do you parse JSON with a colon in the name? Android/Java

For example: { "primary:title":"Little Red Riding Hood"}
My Parser in Java (Android) is always getting stuck because of the colon between primary and title. I can parse anything else with ease, I just need help in this.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView txtViewParsedValue;
private JSONObject jsonObject;
private JSONArray jsonArray;
String [] titles, links, mediaDescriptions, mediaCredits, descriptions, dcCreators, pubDates, categories;
String [] permalinks, texts; // guid
String [] rels, hrefs;
String [] urls, media, heights, widths; // media:content
String strParsedValue = "";
private String strJSONValue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
strJSONValue = readRawTextFile(this, R.raw.jsonextract);
txtViewParsedValue = (TextView) findViewById(R.id.text_view_1);
try {
parseJSON();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseJSON() throws JSONException
{
txtViewParsedValue.setText("Parse 1");
jsonObject = new JSONObject(strJSONValue);
jsonArray = jsonObject.getJSONArray("item");
titles = new String[jsonArray.length()];
links = new String[jsonArray.length()];
permalinks = new String[jsonArray.length()];
texts = new String[jsonArray.length()];
mediaDescriptions = new String[jsonArray.length()];
mediaCredits = new String[jsonArray.length()];
descriptions = new String[jsonArray.length()];
dcCreators = new String[jsonArray.length()];
pubDates = new String[jsonArray.length()];
categories = new String[jsonArray.length()];
txtViewParsedValue.setText("Parse 2");
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
titles[i] = object.getString("title");
links[i] = object.getString("link");
JSONObject guidObj = object.getJSONObject("guid");
permalinks[i] = guidObj.getString("isPermaLink");
texts[i] = guidObj.getString("text");
//mediaDescriptions[i] = object.getString("media:description");
//mediaCredits[i] = object.getString("media:credit");
// *** THE PARSER FAILS IF THE COMMENTED LINES ARE IMPLEMENTED BECAUSE
// OF THE : IN BETWEEN THE NAMES ***
descriptions[i] = object.getString("description");
//dcCreators[i] = object.getString("dc:creator");
pubDates[i] = object.getString("pubDate");
categories[i] = object.getString("category");
}
for (int i=0; i<jsonArray.length(); i++)
{
strParsedValue += "\nTitle: " + titles[i];
strParsedValue += "\nLink: " + links[i];
strParsedValue += "\nPermalink: " + permalinks[i];
strParsedValue += "\nText: " + texts[i];
strParsedValue += "\nMedia Description: " + mediaDescriptions[i];
strParsedValue += "\nMedia Credit: " + mediaCredits[i];
strParsedValue += "\nDescription: " + descriptions[i];
strParsedValue += "\nDC Creator: " + dcCreators[i];
strParsedValue += "\nPublication Date: " + pubDates[i];
strParsedValue += "\nCategory: " + categories[i];
strParsedValue += "\n";
}
txtViewParsedValue.setText(strParsedValue);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
For one, and to answer your question, there is no issue with JSONObject and the org.json.* classes parsing keys with colons in them if they're properly formed. The following unit test passed which means it was able to parse your example scenario:
public void testParsingKeysWithColons() throws JSONException {
String raw = "{ \"primary:title\":\"Little Red Riding Hood\"}";
JSONObject obj = new JSONObject(raw);
String primaryTitle = obj.getString("primary:title");
assertEquals("Little Red Riding Hood", primaryTitle);
}
Another suggestion is that using arrays of Strings for your data is clumsy and you'd be much better organized using a data structure to represent your objects. Instead of string arrays for titles, links, descriptions; use an object that has these properties and make a list of the objects. For example:
public class MyDataStructure {
public String title;
public String primaryTitle;
public String link;
public String mediaDescription;
public static class Keys {
public static String title = "title";
public static String primaryTitle = "primary:title";
public static String link = "link";
public static String mediaDescription = "media:description";
}
}
And then you can make a "translator" class that does all the parsing for you and returns a list of your object. This is much easier to work with and keep track of. You never have to think about data misaligning or having more or less data in one of your arrays than you expected. You also have a much easier time testing where the problem is if your input data is missing anything or any of your json is malformed.
public class MyDataStructureTranslator {
public static List<MyDataStructure> parseJson(String rawJsonData) throws JSONException {
List<MyDataStructure> list = new ArrayList<MyDataStructure>();
JSONObject obj = new JSONObject(rawJsonData);
JSONArray arr = obj.getJSONArray("item");
for(int i = 0; i < arr.length(); i++) {
JSONObject current = arr.getJSONObject(i);
MyDataStructure item = new MyDataStructure();
item.title = current.getString(MyDataStructure.Keys.title);
item.primaryTitle = current.getString(MyDataStructure.Keys.primaryTitle);
item.link = current.getString(MyDataStructure.Keys.link);
item.mediaDescription = current.getString(MyDataStructure.Keys.mediaDescription);
list.add(item);
}
return list;
}
}
Since Java identifiers cannot have colons, just specify a json property name that maps to the exact json name like:
#JsonProperty("primary:title")
public String primaryTitle;

Categories

Resources