I'm trying to iterate through the following JsonObject code in Java , I am using the google gson.
Intent:
In my swing menu, I will press the button labelled with the team name, example:
FC Barcelona
That will then display a list of each player on the respective team button that is pressed.
Example displayed player list:
Bravo, Montoya, Pique, Rakitic , .etc
I am having a hard time understanding how I can go about doing this using this Json file, I'm willing to use any library needed to get the job done, or even reformatting this Json file itself.
EXTRA: If anyone could also explain the basics of navigating through the data so that in the future I can display all the data (age,nationality...) for each player in a team, that would also be great!
{
"Teams":
{
"FC Barcelona":{
"Bravo":{
"age" : "32",
"nationality" : "Chile",
"club" : "FC Barcelona",
"position": "Goalkeeper",
"overall" : "83"
},
"Montoya":{
"age" : "24",
"nationality" : "Spain",
"club" : "FC Barcelona",
"position" : "Defender",
"overall" : "77"
},
"Pique":{
"age" : "28",
"nationality" : "Spain",
"club" : "Barcelona",
"position" : "Defender",
"overall" : "84"
},
"Rakitic":{
"age" : "27",
"nationality" : "Croatia",
"club" : "Barcelona",
"position" : "Midfielder",
"overall" : "83"
},
"Busquets":{
"age" : "27",
"nationality" : "Spain",
"club" : "Barcelona",
"position" : "Midfielder",
"overall" : "86"
},
"Xavi":{
"age" : "35",
"nationality" : "Spain",
"club" : "Barcelona",
"position" : "Midfielder",
"overall" : "86"
},
"Iniesta":{
"age" : "31",
"nationality" : "Spain",
"club" : "Barcelona",
"position" : "Midfielder",
"overall" : ""
},
"Pedro":{
"age" : "28",
"nationality" : "Spain",
"club" : "Barcelona",
"position" : "Forward",
"overall" : "83"
},
"Suarez":{
"age" : "28",
"nationality" : "Uruguay",
"club" : "Barcelona",
"position" : "Forward",
"overall" : "89"
},
"Messi":{
"age" : "28",
"nationality" : "Argentina",
"club" : "Barcelona",
"position" : "Forward",
"overall" : "93"
},
"Neymar":{
"age" : "23",
"nationality" : "Brazil",
"club" : "Barcelona",
"position" : "Forward",
"overall" : "87"
}
}
}
}
I have created one pseudo code check it.
try {
JSONObject root = new JSONObject("YOUR_JSON");
JSONObject team = root.getJSONObject("Teams").getJSONObject("FC Barcelona");
Iterator keys = team.keys();
//iterate each object
while (keys.hasNext()){
JSONObject obj = team.getJSONObject((String)keys.next());
String age = obj.getString("age");
}
} catch (JSONException e) {
e.printStackTrace();
}
This may help you to understand iterating
public class JsonParseTest {
private static final String filePath = "E:\\testJson.json";
public static void main(String[] args) {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
// get a String from the JSON object
String firstName = (String) jsonObject.get("firstname");
System.out.println("The first name is: " + firstName);
// get a number from the JSON object
long id = (long) jsonObject.get("id");
System.out.println("The id is: " + id);
// get an array from the JSON object
JSONArray lang= (JSONArray) jsonObject.get("languages");
// take the elements of the json array
for(int i=0; i<lang.size(); i++){
System.out.println("The " + i + " element of the array: "+lang.get(i));
}
Iterator i = lang.iterator();
// take each value from the json array separately
while (i.hasNext()) {
JSONObject innerObj = (JSONObject) i.next();
System.out.println("language "+ innerObj.get("lang") +
" with level " + innerObj.get("knowledge"));
}
// handle a structure into the json object
JSONObject structure = (JSONObject) jsonObject.get("job");
System.out.println("Into job structure, name: " + structure.get("name"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
This is the json file
{
"id": 1,
"firstname": "Katerina",
"languages": [
{ "lang":"en" , "knowledge":"proficient" },
{ "lang":"fr" , "knowledge":"advanced" },
]
"job":{
"site":"www.javacodegeeks.com",
"name":"Java Code Geeks",
}
}
Related
Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}
I have the following JSON object (sorry for the length) which I need to get the name of the artists. It should be under tracks -> items -> album -> artists -> name. I am trying to run this code but I can't grab the artist name. Here is part of the JSON object:
{
"tracks" : {
"href" : "https://api.spotify.com/v1/search?query=closer&type=track&offset=0&limit=20",
"items" : [ {
"album" : {
"album_type" : "single",
"artists" : [ {
"external_urls" : {
"spotify" : "https://open.spotify.com/artist/69GGBxA162lTqCwzJG5jLp"
},
"href" : "https://api.spotify.com/v1/artists/69GGBxA162lTqCwzJG5jLp",
"id" : "69GGBxA162lTqCwzJG5jLp",
"name" : "The Chainsmokers",
"type" : "artist",
"uri" : "spotify:artist:69GGBxA162lTqCwzJG5jLp"
} ],
"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TR", "TW", "US", "UY" ],
.....
I need to get the line where it says "name" : "The Chainsmokers",, but I can't figure it out. This is what I have so far:
JSONObject jObj;
JSONObject tracks;
JSONArray items;
JSONObject album;
JSONArray artists;
JSONObject aName;
jObj = new JSONObject(json);
tracks = (JSONObject) jObj.get("tracks");
items = (JSONArray) tracks.get("items");
String songName;
Log.d("searchSong", json);
// Return all of the results for the searched song. This will return to a ListView with the song name, uri, and artist name.
for (int i = 0; i < items.length(); i++) {
try {
songName = items.getJSONObject(i).getString("name");
if (!(songName.toLowerCase().contains(query.toLowerCase()))) {
continue;
}
// TODO THIS DOESN'T WORK!!!!
// How do I get artistname????
album = (JSONObject) items.getJSONObject(i).get("album");
artists = album.getJSONArray("artists"); // get the artist name
String artistsName = artists.getJSONObject(4).toString();
String artistName = "";
artistName = artists.getJSONObject(i).getString("name");
// This stuff works
id = items.getJSONObject(i).getString("id");
lViewSearch.setVisibility(View.VISIBLE);
lView.setVisibility(View.INVISIBLE);
bNext.setVisibility(View.INVISIBLE);
bPlay.setVisibility(View.INVISIBLE);
searchSongs.add(songName + "\n" + id);
searchAdapter.notifyDataSetChanged();
svSong.clearFocus();
} catch (JSONException e) {
e.printStackTrace();
}
} // end for loop
This is in a for loop because I need to get all of the songs, here I only posted the JSON object for part of it. Let me know if you see any problems, thanks!
What is artists.getJSONObject(4)? Your array only seems to show one object in the array.
Should just be...
artists.getJSONObject(0).getString("name")
first i have two arrays
ArrayList of type JSONObject jsonArrayResponse, jsonArraySubResponse
note: both arrays have the same size
here is my code to get and insert place data into an array :
for (int i = 0; i<jsonArrayResponse.size() - 1; i++) {
try {
JSONObject objectDictionary = jsonArrayResponse.get(i);
JSONObject objectSubDictionary = jsonArraySubResponse.get(i);
PlaceObject placeObject = new PlaceObject();
placeObject.setPlace_id(objectDictionary.getString("place_id"));
placeObject.setLat(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
placeObject.setLng(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
placeObject.setName(objectDictionary.getString("name"));
if (objectDictionary.has("photos")) {
JSONObject photoReferenceObject = objectDictionary.getJSONArray("photos").getJSONObject(0);
if (photoReferenceObject.has("photo_reference")) {
placeObject.setPhotoReference(photoReferenceObject.getString("photo_reference"));
}
}
if (objectSubDictionary.has("vicinity")) {
placeObject.setVicinity(objectSubDictionary.getString("vicinity"));
}
if (objectSubDictionary.has("formatted_address")) {
placeObject.setFormatted_address(objectSubDictionary.getString("formatted_address"));
}
if (objectSubDictionary.has("formatted_phone_number")) {
placeObject.setFormatted_phone_number(objectSubDictionary.getString("formatted_phone_number"));
}
if (objectSubDictionary.has("international_phone_number")) {
placeObject.setInternational_phone_number(objectSubDictionary.getString("international_phone_number"));
}
if (objectSubDictionary.has("url")) {
placeObject.setUrl(objectSubDictionary.getString("url"));
}
if (objectSubDictionary.has("website")) {
placeObject.setWebsite(objectSubDictionary.getString("website"));
}
if (objectSubDictionary.has("reviews")) {
ArrayList<Reviews> reviews = new ArrayList<Reviews>();
for (int j = 0; j<objectSubDictionary.getJSONArray("reviews").length(); j++) {
Reviews reviewObject = new Reviews();
JSONObject review = objectSubDictionary.getJSONArray("reviews").getJSONObject(j);
reviewObject.setAuthor_name(review.getString("author_name"));
if (review.has("rating")) {
reviewObject.setRating(review.getString("rating"));
}
reviewObject.setText(review.getString("text"));
if (review.has("type")) {
reviewObject.setType(review.getString("type"));
}
reviews.add(reviewObject);
}
placeObject.setReviews(reviews);
}
if (objectDictionary.has("opening_hours")) {
ArrayList<String> days = new ArrayList<String>();
for (int z = 0; z<objectDictionary.getJSONObject("opening_hours").getJSONArray("reviews").length(); z++) {
String day = objectDictionary.getJSONObject("opening_hours").getJSONArray("reviews").getString(z);
days.add(day);
}
placeObject.setWeekday_text(days);
}
if (objectDictionary.has("opening_hours")) {
if (objectDictionary.getJSONObject("opening_hours").has("open_now")) {
placeObject.setOpen_now(objectDictionary.getJSONObject("opening_hours").getBoolean("open_now"));
}
}
Float distanceInKilometers = distance(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lat"), objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lng"), Global.loc.getLatitude(), Global.loc.getLongitude()) / 1000;
placeObject.setDistance(distanceInKilometers.doubleValue());
if (objectDictionary.has("rating")) {
placeObject.setRating(objectDictionary.getDouble("rating"));
}
if (objectDictionary.has("price_level")) {
placeObject.setPrice_level(objectDictionary.getInt("price_level"));
}
placeObjects.add(placeObject);
if (i == jsonArrayResponse.size() - 1) {
this.placeObjectsResopones = placeObjects;
this.placeObjects = placeObjects;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Sample Json data:
1) Places Search request:
{
"html_attributions" : [],
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.870775,
"lng" : 151.199025
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
"id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
"name" : "Rhythmboat Cruises",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 270,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAF-LjFR1ZV93eawe1cU_3QNMCNmaGkowY7CnOf-kcNmPhNnPEG9W979jOuJJ1sGr75rhD5hqKzjD8vbMbSsRnq_Ni3ZIGfY6hKWmsOf3qHKJInkm4h55lzvLAXJVc-Rr4kI9O1tmIblblUpg2oqoq8RIQRMQJhFsTr5s9haxQ07EQHxoUO0ICubVFGYfJiMUPor1GnIWb5i8",
"width" : 519
}
],
"place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "GOOGLE",
"alt_ids" : [
{
"place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "APP"
}
],
"reference" : "CoQBdQAAAFSiijw5-cAV68xdf2O18pKIZ0seJh03u9h9wk_lEdG-cP1dWvp_QGS4SNCBMk_fB06YRsfMrNkINtPez22p5lRIlj5ty_HmcNwcl6GZXbD2RdXsVfLYlQwnZQcnu7ihkjZp_2gk1-fWXql3GQ8-1BEGwgCxG-eaSnIJIBPuIpihEhAY1WYdxPvOWsPnb2-nGb6QGhTipN0lgaLpQTnkcMeAIEvCsSa0Ww",
"types" : [ "travel_agency", "restaurant", "food", "establishment" ],
"vicinity" : "Pyrmont Bay Wharf Darling Dr, Sydney"
},...
],
"status" : "OK"
}
2) Place Details request:
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "48",
"short_name" : "48",
"types" : [ "street_number" ]
},
{
"long_name" : "Pirrama Road",
"short_name" : "Pirrama Road",
"types" : [ "route" ]
},
{
"long_name" : "Pyrmont",
"short_name" : "Pyrmont",
"types" : [ "locality", "political" ]
},
{
"long_name" : "NSW",
"short_name" : "NSW",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "AU",
"short_name" : "AU",
"types" : [ "country", "political" ]
},
{
"long_name" : "2009",
"short_name" : "2009",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "48 Pirrama Road, Pyrmont NSW, Australia",
"formatted_phone_number" : "(02) 9374 4000",
"geometry" : {
"location" : {
"lat" : -33.8669710,
"lng" : 151.1958750
},
"viewport" : {
"northeast" : {
"lat" : -33.8665053,
"lng" : 151.1960371
},
"southwest" : {
"lat" : -33.8669293,
"lng" : 151.1952183
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "4f89212bf76dde31f092cfc14d7506555d85b5c7",
"international_phone_number" : "+61 2 9374 4000",
"name" : "Google Sydney",
"place_id" : "ChIJN1t_tDeuEmsRUsoyG83frY4",
"scope" : "GOOGLE",
"alt_ids" : [
{
"place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "APP"
}
],
"rating" : 4.70,
"reference" : "CnRsAAAA98C4wD-VFvzGq-KHVEFhlHuy1TD1W6UYZw7KjuvfVsKMRZkbCVBVDxXFOOCM108n9PuJMJxeAxix3WB6B16c1p2bY1ZQyOrcu1d9247xQhUmPgYjN37JMo5QBsWipTsnoIZA9yAzA-0pnxFM6yAcDhIQbU0z05f3xD3m9NQnhEDjvBoUw-BdcocVpXzKFcnMXUpf-nkyF1w",
"reviews" : [
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Simon Bengtsson",
"author_url" : "https://plus.google.com/104675092887960962573",
"language" : "en",
"rating" : 5,
"text" : "Just went inside to have a look at Google. Amazing.",
"time" : 1338440552869
},
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Felix Rauch Valenti",
"author_url" : "https://plus.google.com/103291556674373289857",
"language" : "en",
"rating" : 5,
"text" : "Best place to work :-)",
"time" : 1338411244325
},
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Chris",
"language" : "en",
"rating" : 5,
"text" : "Great place to work, always lots of free food!",
"time" : 1330467089039
}
],
"types" : [ "establishment" ],
"url" : "http://maps.google.com/maps/place?cid=10281119596374313554",
"vicinity" : "48 Pirrama Road, Pyrmont",
"website" : "http://www.google.com.au/"
},
"status" : "OK"
}
my problem is i get messing data and i think it skips if data took time to process. how to improve it to make sure i get all data of a place object ?
I note that
inside your loop this condition will not happen
if (i == jsonArrayResponse.size() - 1) {
...
}
because your loop will not continue till i == jsonArrayResponse.size() - 1
try to add = in the loop line like this
for (int i = 0; i <= jsonArrayResponse.size() - 1; i++) { ...}
Maybe this is the reason of missing last element from the array
Please provide sample data. I will try using GSON.
I've been trying to parse this portion of JSON output, but I cannot figure out how to. I'm trying to pull out "140 New Montgomery St". Can anyone tell me how? Below I will include the JSON and my already working JSON parsing code.
{
"businesses" : [{
"display_phone" : "+1-415-908-3801",
"id" : "yelp-san-francisco",
"is_claimed" : true,
"is_closed" : false,
"image_url" : "http://s3-media2.ak.yelpcdn.com/bphoto/7DIHu8a0AHhw-BffrDIxPA/ms.jpg",
"location" : {
"address" : [
"140 New Montgomery St"
],
"city" : "San Francisco",
"neighborhoods" : [
"SOMA"
],
"postal_code" : "94105",
"state_code" : "CA"
},
"mobile_url" : "http://m.yelp.com/biz/4kMBvIEWPxWkWKFN__8SxQ",
"name" : "Yelp",
}
],
"region" : {
"center" : {
"latitude" : 37.786138600000001,
"longitude" : -122.40262130000001
},
"span" : {
"latitude_delta" : 0.0,
"longitude_delta" : 0.0
}
},
"total" : 10651
}
JSONObject json = new JSONObject(rawData);
JSONArray businesses;
businesses = json.getJSONArray("businesses");
for (int i = 0; i < businesses.length(); i++) {
JSONObject business = businesses.getJSONObject(i);
closed = business.get("is_closed").toString();
//...
//...
}
JSONObject location = business.getJSONObject("location");
JSONArray address = location.getJSONArray("address");
String address1 = address.get(0);
//...
//...
I'm trying to geocode an address and get the lat/lng coordinates in java. I'm able to geocode the address and have it return in a json object, but I'm unable to figure out how to use json-simple to parse the json below to get the lat/lng. Any help is appreciated.
{
"results" : [
{
"address_components" : [
{
"long_name" : "Minneapolis",
"short_name" : "Minneapolis",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Hennepin County",
"short_name" : "Hennepin County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Minnesota",
"short_name" : "MN",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Minneapolis, MN, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 45.05125,
"lng" : -93.193794
},
"southwest" : {
"lat" : 44.890144,
"lng" : -93.32916299999999
}
},
"location" : {
"lat" : 44.983334,
"lng" : -93.26666999999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 45.05125,
"lng" : -93.193794
},
"southwest" : {
"lat" : 44.890144,
"lng" : -93.32916299999999
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I've tried many different things, but this is my latest failure:
JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONObject results = (JSONObject) json.get("results"); <-- LINE 186
JSONArray geometry = (JSONArray) results.get("geometry");
for(int i = 0; i < geometry.size(); i++) {
JSONObject p = (JSONObject) geometry.get(i);
System.out.println(p);
}
It produces this stacktrace:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at com.AddressGeocoder.geocode(AddressGeocoder.java:186)
at com.AddressGeocoder.<init>(AddressGeocoder.java:48)
at com.Geocoder.main(Geocoder.java:7)
"results" is a JSONArray filled with (in this example just one) JSONObjects. These JSONObjects contain your expected JSONArray "geometry". Following is your code modified, so it loops through the results and printing the geometry data:
JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONArray results = (JSONArray) json.get("results");
for (int i = 0; i < results.size(); i++) {
// obtaining the i-th result
JSONObject result = (JSONObject) results.get(i);
JSONObject geometry = (JSONObject) result.get("geometry");
JSONObject location = (JSONObject) geometry.get("location");
System.out.println(location.get("lat"));
System.out.println(location.get("lng"));
}
That's because the "results" is a JSONArray. Try:
JSONArray results = (JSONArray ) json.getJSONArray("results");
So let me break it down for you so you can understand in JSON's {} denotes an object [] denotes an array. Simple? Yeah.
visual breakdown
results
index 0 ->
addressed_components(array)-->
long_name(single entity)
short_name(single entity)
types(array)
formatted_address(single entity)
geometry(huge ass object with nested objects)
types(array)
Basically, in the code you have right now results 0 index would contain "address_components", "formatted_address", "geometry", "types". (NOTE THIS IS ALL ONE OBJECT)
"Address_components" is a array.
Which contain multiple "Address_components."
"Geometry" is just a very very large object in which has many different attributes.
Lastly types is an array.
psuedo code to retrieve items from arrays, yo!
LOOP THROUGH JSON ARRAY
ASSIGN OBJECT VALUES // getting different objects that are indexed in the array.
(if you want to see code to see how all this is done let me know)
gl man.
I use net.sf.json library but you can use the logic
Here is the code :
import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
public class Test {
static String str = "{ \"results\" : [ { \"address_components\" : [ { \"long_name\" : \"Minneapolis\", \"short_name\" : \"Minneapolis\", \"types\" : [ \"locality\", \"political\" ] }, { \"long_name\" : \"Hennepin County\", \"short_name\" : \"Hennepin County\", \"types\" : [ \"administrative_area_level_2\", \"political\" ] }, { \"long_name\" : \"Minnesota\", \"short_name\" : \"MN\", \"types\" : [ \"administrative_area_level_1\", \"political\" ] }, { \"long_name\" : \"United States\", \"short_name\" : \"US\", \"types\" : [ \"country\", \"political\" ] } ], \"formatted_address\" : \"Minneapolis, MN, USA\", \"geometry\" : { \"bounds\" : { \"northeast\" : { \"lat\" : 45.05125, \"lng\" : -93.193794 }, \"southwest\" : { \"lat\" : 44.890144, \"lng\" : -93.32916299999999 } }, \"location\" : { \"lat\" : 44.983334, \"lng\" : -93.26666999999999 }, \"location_type\" : \"APPROXIMATE\", \"viewport\" : { \"northeast\" : { \"lat\" : 45.05125, \"lng\" : -93.193794 }, \"southwest\" : { \"lat\" : 44.890144, \"lng\" : -93.32916299999999 } } }, \"types\" : [ \"locality\", \"political\" ] } ], \"status\" : \"OK\"}";
public static void main(String[] args) {
parseAndCheckJsonObj(str, "");
}
static void parseAndCheckJsonObj(Object str, Object key) {
/*
* Check whether str is Valid JSON
* String i.e. started by { [ or not
*/
if (JSONUtils.mayBeJSON(str.toString())) {
try {
if (JSONUtils.isArray(str)) {
/*if block Check for str as a Json Array*/
JSONArray rootArr = JSONArray.fromObject(str);
for (int i = 0; i < rootArr.size(); i++) {
parseAndCheckJsonObj(rootArr.get(i), key);
}
} else {
/*else block Check for str as a Json Object*/
JSONObject rootObj = JSONObject.fromObject(str);
Iterator keyIter = rootObj.keys();
while (keyIter.hasNext()) {
Object objKey = keyIter.next();
parseAndCheckJsonObj(rootObj.get(objKey), objKey);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (key.equals("lat"))
System.out.println("Latitude is : " + str);
else if (key.equals("lng"))
System.out.println("Longitude is : " + str);
else
System.out.println(key + " : " + str);
}
}
}
My Output is :
long_name : Minneapolis
short_name : Minneapolis
types : locality
types : political
long_name : Hennepin County
short_name : Hennepin County
types : administrative_area_level_2
types : political
long_name : Minnesota
short_name : MN
types : administrative_area_level_1
types : political
long_name : United States
short_name : US
types : country
types : political
formatted_address : Minneapolis, MN, USA
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
Latitude is : 44.983334
Longitude is : -93.26666999999999
location_type : APPROXIMATE
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
types : locality
types : political
status : OK