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
Related
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 want to create a JSONObject object from the URL's content,
so I am getting the URL content from the google APIs, that's the result:
"results" : [
{
"address_components" : [
{
"long_name" : "29",
"short_name" : "29",
"types" : [ "street_number" ]
},
{
"long_name" : "Jean",
"short_name" : "Jean",
"types" : [ "route" ]
},
{
"long_name" : "Toulouse",
"short_name" : "Toulouse",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Haute-Garonne",
"short_name" : "31",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Midi",
"short_name" : "Midi",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "France",
"short_name" : "FR",
"types" : [ "country", "political" ]
},
{
"long_name" : "31000",
"short_name" : "31000",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "99 Jean , 31900 Toulouse, France",
"geometry" : {
"location" : {
"lat" : 43.6069496,
"lng" : 1.4498134
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 43.6082985802915,
"lng" : 1.451162380291502
},
"southwest" : {
"lat" : 43.6056006197085,
"lng" : 1.448464419708498
}
}
},
"place_id" : "ChIJTSvW45i8rhIRu8OEgnpnZMY",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
I would like to create a JSONObject from this content , something like
JSONObject obj = JSONObject.fromObject(urlConnection.getInputStream());
but checking the size of this object is 0
You need to read the content of that InputStream to a String, you can't use it directly that way.
Read the InputStream with something similar to this:
public static String slurp(InputStream is){
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
And then use it to get a JSONObject:
JSONObject obj = JSONObject.fromObject(slurp(urlConnection.getInputStream()));
Done !
JSONParser parser = new JSONParser();
Object obj = parser.parse(new InputStreamReader(inputStream));
JSONObject jsonObject = (JSONObject) obj;
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",
}
}
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 have such structure of document:
{
"_id" : "4e76fd1e927e1c9127d1d2e8",
"name" : "***",
"embedPhoneList" : [
{
"type" : "家庭",
"number" : "00000000000"
},
{
"type" : "手机",
"number" : "00000000000"
}
],
"embedAddrList" : [
{
"type" : "家庭",
"addr" : "山东省诸城市***"
},
{
"type" : "工作",
"addr" : "深圳市南山区***"
}
],
"embedEmailList" : [
{
"email" : "********#gmail.com"
},
{
"email" : "********#gmail.com"
},
{
"email" : "********#gmail.com"
},
{
"email" : "********#gmail.com"
}
]
}
What I wan't to do is find the document by it's sub document,such as email in embedEmailList field.
Or if I have structure like this
{
"_id" : "4e76fd1e927e1c9127d1d2e8",
"name" : "***",
"embedEmailList" : [
"123#gmail.com" ,
"********#gmail.com" ,
]
}
the embedEmailList is array,how to find if there is 123#gmail.com?
Thanks.
To search for a specific value in an array, mongodb supports this syntax:
db.your_collection.find({embedEmailList : "foo#bar.com"});
See here for more information.
To search for a value in an embedded object, it supports this syntax:
db.your_collection.find({"embedEmailList.email" : "foo#bar.com"});
See here for more information.