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
Related
I have json file with such form:
{
"Region_1": {
"Area_1": {
"id": "id_1",
"email": "email_1"
},
"Area_2": {
"id": "id_2",
"email": "email_2"
}
},
"Region_2": {
"Area_1": {
"id": "id_1",
"email": "email_1"
},
"Area_2": {
"id": "id_2",
"email": "email_2"
}
}
}
I need to parse this structure using JSONObject, I have already code which parse this but not get Region_2 only.
Region_1 getting.
JSONObject obj = new JSONObject(fileData);
for (Map.Entry<String, Object> entry : obj.entrySet()) {
String region = entry.getKey().toString();
JSONObject areas = new JSONObject(entry.getValue().toString());
System.out.println("region: " + region);
List links = areas.entrySet().collect({ it ->
String area = it.getKey().toString();
System.out.println("area: " + area);
JSONObject areaData = new JSONObject(it.getValue().toString());
String code = areaData.getString("id");
String email = areaData.getString("email");
System.out.println("code: " + code.toString());
System.out.println("email: " + email.toString());
})
}
Why only first object takes from json file ?
I'd like to display values from my JSON just for testing purposes, but I've received literally nothing. Where can be an issue? The link in Utils is correctly for sure, I've runned it on my browser, and everything was good.
Here's the code
Utils class
public class WeatherUtils {
public WeatherUtils(){}
public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){
ArrayList<Weather> weatherList = new ArrayList<>();
try {
JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
JSONArray array = reader.getJSONArray("list");
for (int i = 0; i<array.length(); i++){
JSONObject secondReader = array.getJSONObject(i);
JSONObject dataObject = secondReader.getJSONObject("main");
for (int j = 0; j<dataObject.length(); j++){
currentTemp = dataObject.getDouble("temp");
minTemp = dataObject.getDouble("temp_min");
maxTemp = dataObject.getDouble("temp_max");
airPressure = dataObject.getDouble("pressure");
}
weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
}
} catch (JSONException e) {
e.printStackTrace();
}
return weatherList;
}
}
MainActivity
Double a,b,c,d;
a = 0.0;
b = 0.0;
c = 0.0;
d = 0.0;
ArrayList<Weather> weathers = WeatherUtils.getHourlyData(a,b,c,d);
System.out.println(weathers);
JSON structure
{
"cod": "200",
"message": 0.0074,
"cnt": 40,
"list": [
{
"dt": 1559131200,
"main": {
"temp": 22.1,
"temp_min": 21.32,
"temp_max": 22.1,
"pressure": 1012.31,
"sea_level": 1012.31,
"grnd_level": 976.84,
"humidity": 92,
"temp_kf": 0.78
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": {
"all": 89
},
"wind": {
"speed": 3.08,
"deg": 213.025
},
"rain": {
"3h": 0.875
},
"sys": {
"pod": "d"
},
"dt_txt": "2019-05-29 12:00:00"
},
{
Of course, there are more data. I've posted one "block"
How I may fix that?
Well, given that you just want to "test" the json parsing, you have few options but let's go with a simple one. But first, I would say to extract the parser and put it in its own class/method so it becomes easier to test, something like this:
public class WeatherUtils {
public WeatherUtils(){}
public static ArrayList<Weather> getHourlyData (double minTemp, double maxTemp, double currentTemp, double airPressure){
final ArrayList<Weather> weatherList = new ArrayList<>();
try {
final JSONObject response = httpCall();
weatherList = mapWeatherResponse(response);
} catch (JSONException e) {
e.printStackTrace();
}
return weatherList;
}
public static List<Weather> mapWeatherResponse(JSONObject reader){
final ArrayList<Weather> weatherList = new ArrayList<>();
JSONArray array = reader.getJSONArray("list");
for (int i = 0; i<array.length(); i++){
JSONObject secondReader = array.getJSONObject(i);
JSONObject dataObject = secondReader.getJSONObject("main");
for (int j = 0; j<dataObject.length(); j++){
currentTemp = dataObject.getDouble("temp");
minTemp = dataObject.getDouble("temp_min");
maxTemp = dataObject.getDouble("temp_max");
airPressure = dataObject.getDouble("pressure");
}
weatherList.add(new Weather(currentTemp,minTemp,maxTemp,airPressure));
}
}
}
Test the response parser with a junit test:
You can create a junit test like this:
public class WeatherUtilsTest {
#Test
public void parserResponseTEst() {
final List<String> expectedResponse = new ArrayList<>();
//fill the expectedResponse with the correspondent values
final String json = "{\n" +
" \"cod\": \"200\",\n" +
" \"message\": 0.0074,\n" +
" \"cnt\": 40,\n" +
" \"list\": [\n" +
" {\n" +
" \"dt\": 1559131200,\n" +
" \"main\": {\n" +
" \"temp\": 22.1,\n" +
" \"temp_min\": 21.32,\n" +
" \"temp_max\": 22.1,\n" +
" \"pressure\": 1012.31,\n" +
" \"sea_level\": 1012.31,\n" +
" \"grnd_level\": 976.84,\n" +
" \"humidity\": 92,\n" +
" \"temp_kf\": 0.78\n" +
" },\n" +
" \"weather\": [\n" +
" {\n" +
" \"id\": 500,\n" +
" \"main\": \"Rain\",\n" +
" \"description\": \"light rain\",\n" +
" \"icon\": \"10d\"\n" +
" }\n" +
" ],\n" +
" \"clouds\": {\n" +
" \"all\": 89\n" +
" },\n" +
" \"wind\": {\n" +
" \"speed\": 3.08,\n" +
" \"deg\": 213.025\n" +
" },\n" +
" \"rain\": {\n" +
" \"3h\": 0.875\n" +
" }\n" +
" }]\n" +
" }";
final List<String> response = WeatherUtils.mapWeatherResponse(new JSONObject(json));
assertEquals(expectedResponse, response);
}
}
There is nothing wrong with the JSONObject parser you are doing. You mentioned the link you are using in Utils is correct, do you get a proper response when you test it in your browser, postman, insomnia?
OBS JSONObject reader = new JSONObject("https://api..."); does not fetch anything, what you are doing there is creating a JSONObject from the given String, i.e. "https://....". To fetch the data you need to implement some http client. Here is an example https://stackoverflow.com/a/4457526/761668
You're not getting the response from the server, you're trying to initialize a JSONObject with the URL.
To retrieve it you should replace this line:
JSONObject reader = new JSONObject("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...");
with this code:
HttpURLConnection conn = null;
String data = null;
try {
conn = (HttpURLConnection) new URL("https://api.openweathermap.org/data/2.5/forecast?q=London,us&units=metric&appid=ID...").openConnection();
conn.setRequestMethod("GET");
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
data = sb.toString();
} catch (Exception e) {
// do something
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
// do something
}
}
}
JSONObject reader = new JSONObject(data);
This code will retrieve the JSON object from the endpoint and convert it to a String object. Then you can create a JSONObject with it.
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")
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();
}
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"