This is my below code from which I need to parse the JSONObject to get individual items. This is the first time I am working with JSON. So not sure how to parse JSONObject to get the individual items from JSONObject.
try {
String url = service + version + method + ipAddress + format;
StringBuilder builder = new StringBuilder();
httpclient = new DefaultHttpClient();
httpget = new HttpGet(url);
httpget.getRequestLine();
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jsonObject = new JSONObject(builder.toString());
// Now iterate jsonObject to get Latitude,Longitude,City,Country etc etc.
}
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getMessage());
} finally {
bufferedReader.close();
httpclient.getConnectionManager().shutdown();
}
My JSON looks like this:
{
"ipinfo": {
"ip_address": "131.208.128.15",
"ip_type": "Mapped",
"Location": {
"continent": "north america",
"latitude": 30.1,
"longitude": -81.714,
"CountryData": {
"country": "united states",
"country_code": "us"
},
"region": "southeast",
"StateData": {
"state": "florida",
"state_code": "fl"
},
"CityData": {
"city": "fleming island",
"postal_code": "32003",
"time_zone": -5
}
}
}
}
I need to get latitude, longitude, city, state, country, postal_code from the above object. Can anyone provide any suggestion how to do it efficiently?
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"
Related
I am learning about jsonobject in java. I want to print value from json object. I am reading from URL and the storing into hashmap. but now I do I print particulate value like term and type.
I WANT TO PRINT TERM AND TYPE FROM HASHMAP WHICH I AM CREATING.
Here is my code
Here is my response from URL
{
"neighborhoods": {
"label": "abc",
"value": []
},
"communities": {
"label": "xyz",
"value": {
"83": {
"label": "San Francisco Bay Area, California 94538",
"value": 83,
"type": "community",
"term": "abc"
},
"94": {
"label": "San Francisco Bay Area, California 94538",
"value": 94,
"type": "community",
"term": "II"
}
}
}
}
public static void main(String[] args) {
try {
String url = "Removing URL and added json response which getting above the code";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in =new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readL***strong text***ine()) != null) {
response.append(inputLine);
} in .close();
//print in String
System.out.println(response.toString());
JSONObject myresponse = new JSONObject(response.toString());
System.out.println(myresponse);
JSONObject neighborhoods_object = new JSONObject(myresponse.getJSONObject("neighborhoods").toString());
System.out.println("\n\nNeighborhoods Objects -" + neighborhoods_object);
JSONObject communities_object = new JSONObject(myresponse.getJSONObject("communities").toString());
System.out.println("\nCommunities Objects -" + communities_object);
System.out.println("Text from Label " + communities_object.getString("label"));
JSONObject value_object1 = new JSONObject(communities_object.getJSONObject("value").toString());
System.out.println("\nCommunities Objects and within that Value Object-" + value_object1);
Map<String, Object> result = new HashMap<String, Object>();
System.out.println("Length " + value_object1.length());
Iterator<String> keysItr = value_object1.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = value_object1.get(key);
result.put(key, value);
}
for(Map.Entry<String, Object> entry : result.entrySet())
{
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
// JSONObject neighborhoods_object2 = new JSONObject(value_object1.getJSONObject("83").toString());
// System.out.println("\n\nNeighborhoods Objects 2-" + neighborhoods_object2);
//
// JSONObject neighborhoods_object3 = new JSONObject(value_object1.getJSONObject("83").toString());
// System.out.println("Value of Label-" + neighborhoods_object3.getString("label"));
// System.out.println("Value of -" + neighborhoods_object3.getInt("value"));
// System.out.println("Type -" + neighborhoods_object3.getString("type"));
// System.out.println("Short Term-" + neighborhoods_object3.getString("term"));
}
} catch(Exception e) {
System.out.println(e);
}
}
{
"neighborhoods": {
"label": "Neighborhoods",
"value": []
},
"communities": {
"label": "Communities",
"value": {
"83": {
"label": "Mission Peaks - San Francisco Bay Area, California 94538",
"value": 83,
"type": "community",
"term": "Mission Peaks"
},
"94": {
"label": "Mission Peaks II - San Francisco Bay Area, California 94538",
"value": 84,
"type": "community",
"term": "Mission Peaks II"
}
}
}
}
This can be enough for you to get the details out of your json object
urlConnection.connect();
is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
jObj = new JSONObject(json);
After that just use
jObj.getString("key");
or any type of variable you want
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")
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();
}
});
}
This is the JSON response I am getting using Foursquare API. Here, I am able to extract names of different venues using "name" tag and display as listview. But, the issue is I am not able to extract data from "location" tag given in JSON response.
This is how I am getting names of venues:
jsonResponse = new JSONObject(json.toString());
jsonResponse = jsonResponse.getJSONObject("response");
// products found
// Getting Array of Products
cinemas = jsonResponse.getJSONArray(TAG_PRODUCTS);//response
// looping through All Products
for (int i = 0; i < cinemas.length(); i++) {
JSONObject venueObject = cinemas.getJSONObject(i);
// String id = venueObject.getString(TAG_PID);
String name = venueObject.getString(TAG_NAME);
prgmName.add(name);
}
JSON response:
{
"response": {
"venues": [
{
"referralId": "v1404154392",
"id": "52cd70b711d279a93b2761ac",
"location": {
"formattedAddress": [
"",
"India"
],
"distance": 635,
"lng": 70.79618019123747,
"cc": "IN",
"lat": 22.302471281197825,
"country": "India"
},
"stats": {
"checkinsCount": 24,
"tipCount": 0,
"usersCount": 14
},
"verified": false,
"name": "R WORLD BIG CINEMA",
"categories": [
{
"id": "4bf58dd8d48988d180941735",
"icon": {
"suffix": ".png",
"prefix": "https://ss1.4sqi.net/img/categories_v2/arts_entertainment/movietheater_"
},
"shortName": "Cineplex",
"pluralName": "Multiplexes",
"primary": true,
"name": "Multiplex"
}
],
"hereNow": {
"summary": "0 people here",
"count": 0,
"groups": []
},
"contact": {},
"specials": {
"count": 0,
"items": []
}
}
]
},
"meta": {
"code": 200
}
}
Any help in this regard will be great.
try {
objMain = new JSONObject(response);
JSONObject objRes=objMain.getJSONObject("response");
JSONArray arrVenues=objRes.getJSONArray("venues");
JSONObject obj=arrVenues.getJSONObject(0);
JSONObject objLocation=obj.getJSONObject("location");
Double lat=objLocation.getDouble("lat");
Double lnt=objLocation.getDouble("lng");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use getJSONObject again onvenueObject`:
Try this for example:
jsonResponse = new JSONObject(json.toString());
jsonResponse = jsonResponse.getJSONObject("response");
// products found
// Getting Array of Products
cinemas = jsonResponse.getJSONArray(TAG_PRODUCTS);//response
// looping through All Products
for (int i = 0; i < cinemas.length(); i++) {
JSONObject venueObject = cinemas.getJSONObject(i);
String name = venueObject.getString(TAG_NAME);
JSONObject location = venueObject. getJSONObject(TAG_LOCATION);
String countryCode = location.getString("cc");
prgmName.add(name);
}
location is an json object again in the results array so you have to modify your code:-
for (int i = 0; i < cinemas.length(); i++)
{
JSONObject venueObject = cinemas.getJSONObject(i);
String name = venueObject.getString(TAG_NAME);
JSONObject find_location=venueObject.getJSONObject("location");
String lat = find_location.getString("lat");
String lon = find_location.getString("lng");
prgmName.add(name);
}
jsonResponse = new JSONObject(json.toString());
jsonResponse = jsonResponse.getJSONObject("response");
cinemas = jsonResponse.getJSONArray(TAG_PRODUCTS);//response
for (int i = 0; i < cinemas.length(); i++)
{
JSONObject venue = cinemas.getJSONObject(i);
String name = venue.getString(TAG_NAME);
JSONObject loc = venue. getJSONObject(TAG_LOCATION);
String countryCode = location.getString(3);
String lat = loc.getString("lat");
String lon = loc.getString("lng");
prgmName.add(name);
}
Try this way,hope this will help you to solve your problem.
String jsonStr ="{\"response\":{\"venues\":[{\"referralId\":\"v1404154392\",\"id\":\"52cd70b711d279a93b2761ac\",\"location\":{\"formattedAddress\":[\"\",\"India\"],\"distance\":635,\"lng\":70.79618019123747,\"cc\":\"IN\",\"lat\":22.302471281197825,\"country\":\"India\"},\"stats\":{\"checkinsCount\":24,\"tipCount\":0,\"usersCount\":14},\"verified\":false,\"name\":\"R WORLD BIG CINEMA\",\"categories\":[{\"id\":\"4bf58dd8d48988d180941735\",\"icon\":{\"suffix\":\".png\",\"prefix\":\"https:\\/\\/ss1.4sqi.net\\/img\\/categories_v2\\/arts_entertainment\\/movietheater_\"},\"shortName\":\"Cineplex\",\"pluralName\":\"Multiplexes\",\"primary\":true,\"name\":\"Multiplex\"}],\"hereNow\":{\"summary\":\"0 people here\",\"count\":0,\"groups\":[]},\"contact\":{},\"specials\":{\"count\":0,\"items\":[]}}]},\"meta\":{\"code\":200}}";
try {
JSONObject respone = new JSONObject(jsonStr);
String code = respone.getJSONObject("meta").getString("code");
JSONArray jsonArr = respone.getJSONObject("response").getJSONArray("venues");
ArrayList<HashMap<String,Object>> list = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < jsonArr.length(); i++) {
HashMap<String, Object> venueMap = new HashMap<String, Object>();
venueMap.put("referralId", jsonArr.getJSONObject(i).getString("referralId"));
venueMap.put("id", jsonArr.getJSONObject(i).getString("id"));
venueMap.put("verified", jsonArr.getJSONObject(i).getString("verified"));
venueMap.put("name", jsonArr.getJSONObject(i).getString("name"));
HashMap<String,Object> locationMap = new HashMap<String, Object>();
locationMap.put("distance", jsonArr.getJSONObject(i).getJSONObject("location").getString("distance"));
locationMap.put("lng", jsonArr.getJSONObject(i).getJSONObject("location").getString("lng"));
locationMap.put("cc", jsonArr.getJSONObject(i).getJSONObject("location").getString("cc"));
locationMap.put("lat", jsonArr.getJSONObject(i).getJSONObject("location").getString("lat"));
locationMap.put("country", jsonArr.getJSONObject(i).getJSONObject("location").getString("country"));
ArrayList<String> formattedAddressList = new ArrayList<String>();
JSONArray formattedAddressJsonArray = jsonArr.getJSONObject(i).getJSONObject("location").getJSONArray("formattedAddress");
for(int j=0;j<formattedAddressJsonArray.length();j++){
formattedAddressList.add(formattedAddressJsonArray.getString(j));
}
locationMap.put("formattedAddress",formattedAddressList);
venueMap.put("location",locationMap);
HashMap<String,Object> statsMap = new HashMap<String, Object>();
statsMap.put("distance", jsonArr.getJSONObject(i).getJSONObject("stats").getString("checkinsCount"));
statsMap.put("tipCount", jsonArr.getJSONObject(i).getJSONObject("stats").getString("tipCount"));
statsMap.put("usersCount", jsonArr.getJSONObject(i).getJSONObject("stats").getString("usersCount"));
venueMap.put("stats",statsMap);
ArrayList<HashMap<String,Object>> categoriesList = new ArrayList<HashMap<String, Object>>();
JSONArray categoriesJsonArray = jsonArr.getJSONObject(i).getJSONArray("categories");
for(int j=0;j<categoriesJsonArray.length();j++) {
HashMap<String, Object> categoryMap = new HashMap<String, Object>();
categoryMap.put("id", categoriesJsonArray.getJSONObject(j).getString("id"));
categoryMap.put("shortName", categoriesJsonArray.getJSONObject(j).getString("shortName"));
HashMap<String,String> iconMap = new HashMap<String, String>();
iconMap.put("suffix", categoriesJsonArray.getJSONObject(j).getJSONObject("icon").getString("suffix"));
iconMap.put("prefix", categoriesJsonArray.getJSONObject(j).getJSONObject("icon").getString("prefix"));
categoryMap.put("icon", iconMap);
categoryMap.put("pluralName", categoriesJsonArray.getJSONObject(j).getString("pluralName"));
categoryMap.put("primary", categoriesJsonArray.getJSONObject(j).getString("primary"));
categoryMap.put("name", categoriesJsonArray.getJSONObject(j).getString("name"));
categoriesList.add(categoryMap);
}
venueMap.put("categories",categoriesList);
HashMap<String,Object> hereNowMap = new HashMap<String, Object>();
hereNowMap.put("summary", jsonArr.getJSONObject(i).getJSONObject("hereNow").getString("summary"));
hereNowMap.put("count", jsonArr.getJSONObject(i).getJSONObject("hereNow").getString("count"));
ArrayList<String> groupsList = new ArrayList<String>();
JSONArray groupsJsonArray = jsonArr.getJSONObject(i).getJSONObject("hereNow").getJSONArray("groups");
for(int j=0;j<groupsJsonArray.length();j++){
groupsList.add(groupsJsonArray.getString(j));
}
hereNowMap.put("groups",groupsList);
venueMap.put("hereNow",hereNowMap);
JSONObject contact = jsonArr.getJSONObject(i).getJSONObject("contact");
HashMap<String,Object> specialsMap = new HashMap<String, Object>();
specialsMap.put("count", jsonArr.getJSONObject(i).getJSONObject("specials").getString("count"));
ArrayList<String> itemsList = new ArrayList<String>();
JSONArray itemsJsonArray = jsonArr.getJSONObject(i).getJSONObject("specials").getJSONArray("items");
for(int j=0;j<itemsJsonArray.length();j++){
itemsList.add(itemsJsonArray.getString(j));
}
specialsMap.put("items",itemsList);
venueMap.put("specials",specialsMap);
list.add(venueMap);
}
System.out.print("Code: " + code);
for (HashMap<String,Object> venue : list){
System.out.print("referralId : " + venue.get("referralId"));
System.out.print("id : " + venue.get("id"));
System.out.print("verified : " + venue.get("verified"));
System.out.print("name : " + venue.get("name"));
HashMap<String,Object> locationMap = (HashMap<String,Object>)venue.get("location");
System.out.print("distance : " + locationMap.get("distance"));
System.out.print("lng : " + locationMap.get("lng"));
System.out.print("cc : " + locationMap.get("cc"));
System.out.print("lat : " + locationMap.get("lat"));
System.out.print("country : " + locationMap.get("country"));
ArrayList<String> formattedAddressList = (ArrayList<String>) locationMap.get("formattedAddress");
for (String formattedAddress : formattedAddressList){
System.out.print("formattedAddress : " +formattedAddress);
}
HashMap<String,Object> statsMap = (HashMap<String,Object>)venue.get("stats");
System.out.print("distance : " + statsMap.get("distance"));
System.out.print("tipCount : " + statsMap.get("lng"));
System.out.print("usersCount : " + statsMap.get("cc"));
ArrayList<HashMap<String,Object>> categoriesList = (ArrayList<HashMap<String,Object>>)venue.get("categories");
for (HashMap<String,Object> category : categoriesList){
System.out.print("id : " + category.get("id"));
System.out.print("shortName : " + category.get("shortName"));
System.out.print("shortName : " + category.get("shortName"));
HashMap<String,Object> icon = (HashMap<String,Object>)category.get("icon");
System.out.print("icon suffix: " + icon.get("suffix"));
System.out.print("icon prefix: " + icon.get("prefix"));
System.out.print("pluralName : " + category.get("pluralName"));
System.out.print("primary : " + category.get("primary"));
System.out.print("name : " + category.get("name"));
}
HashMap<String,Object> hereNowMap = (HashMap<String,Object>)venue.get("hereNow");
System.out.print("summary : " + hereNowMap.get("summary"));
System.out.print("count : " + hereNowMap.get("count"));
ArrayList<String> groupsList = (ArrayList<String>) hereNowMap.get("groups");
for (String group : groupsList){
System.out.print("group : " +group);
}
HashMap<String,Object> specialsMap = (HashMap<String,Object>)venue.get("specials");
System.out.print("count : " + specialsMap.get("summary"));
ArrayList<String> itemsList = (ArrayList<String>) specialsMap.get("items");
for (String item : itemsList){
System.out.print("item : " +item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
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.