how to get lng and lat from JSON file - android

I would like to get "lat" and "lng" from my JSON file and add to one array that keeps GeoPoint. I was trying to do it like that but it is not working for me :
protected List<GeoPoint> JsonArray(){
List<GeoPoint> endp = new ArrayList<GeoPoint>();
try{
JSONObject obj = new JSONObject(json);
JSONArray steps = obj.getJSONArray("routes");
for(int i=0;i<steps.length();i++){
JSONObject temp = steps.getJSONObject(i);
JSONObject ele = temp.optJSONObject("steps").optJSONObject("end_location");
ele.getJSONObject("lat");
ele.getJSONObject("lng");
double lat = Double.parseDouble(ele.getJSONObject("lat").toString());
double lng = Double.parseDouble(ele.getJSONObject("lng").toString());
endp.add(new GeoPoint((int)(lat *1E6),(int)(lng * 1E6)));
}
}catch (JSONException e) {
// TODO: handle exception
}
return endp;
}
Here's a part of how looks my JSON file:
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 41.87999000000001,
"lng" : -87.615020
},
"southwest" : {
"lat" : 29.74674000000001,
"lng" : -95.361220
}
},
"copyrights" : "Dane do Mapy ©2013 Google",
"legs" : [
{
"distance" : {
"text" : "1 085 mil",
"value" : 1746457
},
"duration" : {
"text" : "16 godz. 39 min",
"value" : 59955
},
"end_address" : "1362 Chenevert Street, Houston, Teksas 77003, Stany Zjednoczone",
"end_location" : {
"lat" : 29.750110,
"lng" : -95.36016000000001
},
"start_address" : "138-230 South Columbus Drive, Chicago, Illinois 60601, Stany Zjednoczone",
"start_location" : {
"lat" : 41.87999000000001,
"lng" : -87.62075000000002
},
"steps" : [
{
"distance" : {
"text" : "338 stóp",
"value" : 103
},
"duration" : {
"text" : "1 min",
"value" : 9
},
"end_location" : {
"lat" : 41.88090,
"lng" : -87.62069000000001
},
"html_instructions" : "Kieruj się \u003cb\u003eS Columbus Dr\u003c/b\u003e na \u003cb\u003epółnoc\u003c/b\u003e w stronę \u003cb\u003eE Monroe St\u003c/b\u003e",
"polyline" : {
"points" : "}tr~FtlxuOuA#w##QMUA"
},
"start_location" : {
"lat" : 41.87999000000001,
"lng" : -87.62075000000002
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0,2 mil",
"value" : 266
},
"duration" : {
"text" : "1 min",
"value" : 33
},
"end_location" : {
"lat" : 41.88086000000001,
"lng" : -87.61750000000001
},
"html_instructions" : "Skręć \u003cb\u003ew prawo\u003c/b\u003e w \u003cb\u003eE Monroe St\u003c/b\u003e",
"polyline" : {
"points" : "szr~FhlxuO?SAyA?_B#yA?iBAaB?WBE#C#A?C?A#A?C?y#?_#"
},
"start_location" : {
"lat" : 41.88090,
"lng" : -87.62069000000001
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "2,0 mil",
"value" : 3186
},
"duration" : {
"text" : "3 min",
"value" : 180
},
"end_location" : {
"lat" : 41.85320,
"lng" : -87.61470000000001
},
"html_instructions" : "Skręć \u003cb\u003ew prawo\u003c/b\u003e w \u003cb\u003eU.S. 41 S\u003c/b\u003e",
"polyline" : {
"points" : "kzr~FjxwuOpMOZ#`PO|ACvDC#?lDCZAfMGjAA`#Av#?^?P?N#P#j#LRFNDRJRHZRb#\\b#^nAjA##JJXXb#b#z#v#RRp#`#RLr#Xn#Np#J`A#bBOp#Kv#K#?#?#A#?#?#?#?PEvBWxB]fDq#xA]jF_BTIj#QpGuBd#OBAf#SrDyAPGNG#AVKbA_#~#]|#]z#Y`F{AtCy#fHyB"
},
"start_location" : {
"lat" : 41.88086000000001,
"lng" : -87.61750000000001
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0,4 mil",
"value" : 581
},
"duration" : {
"text" : "1 min",
"value" : 30
},
"end_location" : {
"lat" : 41.848390,
"lng" : -87.614670
},
"html_instructions" : "Zjedź \u003cb\u003eInterstate 55 S\u003c/b\u003e w kierunku \u003cb\u003eSaint Louis\u003c/b\u003e",
"polyline" : {
"points" : "omm~FzfwuOVDPAN?VGlBk#b#M#?JEDAVI`A[dBi#`A[z#UPGZGf#E\\Ab##VDJBHBTFTHRJPNRNLL\\f#NXLTP\\BF"
},
"start_location" : {
"lat" : 41.85320,
"lng" : -87.61470000000001
},
"travel_mode" : "DRIVING"
},
Does anyone knows how can I do it in other way?

Your variable JSONArray steps = obj.getJSONArray("routes"); does not represent the "steps" part of the JSON object, but rather the "routes" part.
Also, you have skipped some of the levels in the JSON hierarchy. With the given JSON, you would need the following steps to traverse the JSON (I have omitted looping over the different arrays, except for the routes array)
JSONArray routes = obj.getJSONArray("routes");
for(int i=0; i < routes.length(); i++){
// Grab the first route
JSONObject route = routesArray.getJSONObject(i);
// Take all legs from the route
JSONArray legs = route.getJSONArray("legs");
// Grab first leg
JSONObject leg = legs.getJSONObject(0);
// Take all steps from the leg
JSONArray steps = leg.getJSONArray("steps");
// Grab first step
JSONObject step = steps.getJSONObject(0);
JSONObject endLocation = step.getJSONObject("end_location");
String lat = endLocation.getString("lat");
String lng = endLocation.getString("lng");
Reference: JSON parsing of Google Maps API in Android App

parse current json String as to get lat and lng :
JSONObject obj = new JSONObject(json);
JSONArray steps = obj.getJSONArray("routes");
for(int i=0;i<steps.length();i++){
JSONObject temp = steps.getJSONObject(i);
// get bounds JSONObject
JSONObject boundsjsonobj = temp.getJSONObject("bounds");
// get northeast JSONObject
JSONObject jsonboj_bounds_northeast= boundsjsonobj.getJSONObject("northeast");
// get northeast lng and lat
String str_northeast_lat=jsonboj_bounds_northeast.getString("lat");
String str_northeast_lng=jsonboj_bounds_northeast.getString("lng");
// get southwest JSONObject
JSONObject jsonboj_bounds_southwest= boundsjsonobj.getJSONObject("southwest");
// get northeast lng and lat
String str_southwest_lat=jsonboj_bounds_southwest.getString("lat");
String str_southwest_lng=jsonboj_bounds_southwest.getString("lng");
//get legs JsonArray from routes
JSONArray jsonarray_legs = temp.getJSONArray("legs");
for(int j=0;j<jsonarray_legs.length();j++){
JSONObject jobjlegs = jsonarray_legs.getJSONObject(j);
// get end_location json object
JSONObject jobjlegs_end_location = jobjlegs.getJSONObject("end_location");
String str_end_location_lat==jobjlegs_end_location.getString("lat");
String str_end_location_lng==jobjlegs_end_location.getString("lng");
// get start_address object
JSONObject jobjlegs_start_address = jobjlegs.getJSONObject("start_address");
String str_start_address_lat==jobjlegs_start_address.getString("lat");
String str_start_address_lng==jobjlegs_start_address.getString("lng");
// get steps jsonArray
JSONArray jsonarray_steps = jobjlegs.getJSONArray("steps");
for(int k=0;k<jsonarray_steps.length();k++){
JSONObject jobjsteps = jsonarray_steps.getJSONObject(k);
// get end_location jsonobject
JSONObject jobjsteps_end_location = jobjsteps.getJSONObject("end_location");
double latend = Double.parseDouble(jobjsteps_end_location.getString("lat"));
double lngend = Double.parseDouble(jobjsteps_end_location.getString("lng"));
endp.add(new GeoPoint((int)(latend *1E6),(int)(lngend * 1E6)));
// get start_location jsonobject
JSONObject jobjsteps_start_location = jobjsteps.getJSONObject("start_location");
double latstart = Double.parseDouble(jobjsteps_start_location.getString("lat"));
double lngstart = Double.parseDouble(jobjsteps_start_location.getString("lng"));
}
}
}

Related

Android Studio - Parse from JSON ( Google Maps Api)

I need to extract the location type from where I am on the map for example from the following JSON :
(I deleted some of the irrelevant information in the fields)
{ "html_attributions" : [],
"results" : [
{ "business_status" : "OPERATIONAL", "geometry" :
{ "location" : { "lat" : 31.7895094,"lng" : 34.6444928},
"viewport" :
{"northeast" : {"lat" : 31.790,"lng" : 34.645}, "southwest" : {"lat" : 31.788,"lng" : 34.643} } },
"icon_mask_base_uri" : "",
"name" : "",
"opening_hours" : {"open_now" : true },
"photos" : [ { "height" : 709,
"html_attributions" : [],
"photo_reference" : "", "width" : 960 }],
"place_id" : "",
"plus_code" : {"compound_code" : "QJQV+RQ Ashdod, Israel",
"global_code" : "8G3PQJQV+RQ"},
"rating" : 3.9,
"reference" : "","scope" : "GOOGLE",
"types" : [ "electrician", "point_of_interest", "establishment" ],
"user_ratings_total" : 18,
"vicinity" : ""}],
"status" : "OK"}
I'm having trouble because the location type can be empty or can be a single location or can be several location types that come in an array.
The cases I need to handle:
If it's an array, I want only the first type (as in the attached example)
If it is a single location I want to extract it
If there is no location do not try to extract a location type at all
In the example above i need extract only "electrician" from types
This is how my code looks without extracting the types field:
public class FetchData extends AsyncTask<Object,String,String> {
String googleNearByPlacesData ;
GoogleMap googleMap;
String url;
String temp;
#Override
protected void onPostExecute(String s) {
//This is the exampale print
Log.d("json?" ,s);
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i= 0 ; i < jsonArray.length() ; i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject getLocation = jsonObject1.getJSONObject("geometry").
getJSONObject("location");
String lat = getLocation.getString("lat");
String lng = getLocation.getString("lng");
JSONObject getName = jsonArray.getJSONObject(i);
String name = getName.getString("name");
LatLng latLng = new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
MarkerOptions maekerOptions = new MarkerOptions();
maekerOptions.title(name);
maekerOptions.position(latLng);
googleMap.addMarker(maekerOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Trouble Getting LatLng from Google places json array object

The Problem I seem to be having is accessing the "deeper level" lat lng values from within the json file.
The Json file is being accessed live from google with this type of link:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?
Here is what a single object/array item looks like in json, including the "top Level" "results".
"results" : [
{
"geometry" : {
"location" : {
"lat" : 55.4628609,
"lng" : -4.6299348
},
"viewport" : {
"northeast" : {
"lat" : 55.46420472989273,
"lng" : -4.628674020107278
},
"southwest" : {
"lat" : 55.46150507010728,
"lng" : -4.631373679892723
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
"id" : "0655ceeeddd83f1a901bcef361b22cbfa951ae73",
"name" : "GAME",
"opening_hours" : {
"open_now" : false
},
"place_id" : "ChIJM8hBpZ3WiUgRuWc3KhfMJys",
"plus_code" : {
"compound_code" : "F97C+42 Ayr, UK",
"global_code" : "9C7QF97C+42"
},
"rating" : 4.2,
"reference" : "ChIJM8hBpZ3WiUgRuWc3KhfMJys",
"scope" : "GOOGLE",
"types" : [ "electronics_store", "store", "point_of_interest", "establishment" ],
"vicinity" : "120 High St, Ayr"
},
Here is the Method im using to access the json file data after it has been parsed to string.
void createMarkersFromJson(String json) throws JSONException {
JSONObject object = new JSONObject(json);
JSONArray jsonArray = object.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.position(new LatLng(
jsonObj.getJSONArray("geometry").getDouble(0),
jsonObj.getJSONArray("geometry").getDouble(1)
))
);
}
}
Geometry is not an array. JSON that begins with CURLY BRACE {} is an object while BRACKET [ ] indicates an array. Try this one.
JSONArray jsonArray= object.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject locationObj = jsonObj .getJSONObject("geometry")
.getJSONObject("location");
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.position(new LatLng(
locationObj.getDouble("lat"),
locationObj.getDouble("lng")
))
);
}
Hope this helps you clarify difference between JSON array and object, and how to access them. Cheers

Get multiple Objects from Json Android

I want to get data from this but its to confusing, how to do it.
I want to access legs. In legs distance then text.
Then after steps, in steps again distance and then text.
In "routes" ==> "legs" --> distance --> text
Then to get driving steps
"routes" ==> "legs" ==> "steps" --> distance --> text
First there is object then array again object its too confusing. Any help would be appreciated.
{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI",
"types" : [ "locality", "political" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o",
"types" : [ "locality", "political" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"southwest" : {
"lat" : 30.1981178,
"lng" : 71.4687352
}
},
"copyrights" : "Map data ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "348 km",
"value" : 347978
},
"duration" : {
"text" : "4 hours 49 mins",
"value" : 17335
},
"end_address" : "Multan, Pakistan",
"end_location" : {
"lat" : 30.1981178,
"lng" : 71.4687352
},
"start_address" : "Lahore, Pakistan",
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"steps" : [
{
"distance" : {
"text" : "67 m",
"value" : 67
},
"duration" : {
"text" : "1 min",
"value" : 9
},
"end_location" : {
"lat" : 31.5549532,
"lng" : 74.3565735
},
"html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e",
"polyline" : {
"points" : "k_r_Ei{ydM[r#e#bA"
},
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"travel_mode" : "DRIVING"
},
Manual method:
In few words Json gives you objects (beetwen { } ) or array (beetwen [ ] ). To get sth from deep in json you have to go through each level. You put only fragment of json, but I closed it and we have at start json object (because main braces are {} ):
{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI",
"types" : [ "locality", "political" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o",
"types" : [ "locality", "political" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"southwest" : {
"lat" : 30.1981178,
"lng" : 71.4687352
}
},
"copyrights" : "Map data ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "348 km",
"value" : 347978
},
"duration" : {
"text" : "4 hours 49 mins",
"value" : 17335
},
"end_address" : "Multan, Pakistan",
"end_location" : {
"lat" : 30.1981178,
"lng" : 71.4687352
},
"start_address" : "Lahore, Pakistan",
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"steps" : [
{
"distance" : {
"text" : "67 m",
"value" : 67
},
"duration" : {
"text" : "1 min",
"value" : 9
},
"end_location" : {
"lat" : 31.5549532,
"lng" : 74.3565735
},
"html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e",
"polyline" : {
"points" : "k_r_Ei{ydM[r#e#bA"
},
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"travel_mode" : "DRIVING"
}]
}
]
}
]
}
Let's say you have this as a String named "jsonString". You create json object like this:
JSONObject jsonObject = new JSONObject(jsonString);
Than you needs "routes" that is json array (between [] braces). You create this array going deeper into your main jsonObject:
JSONArray routesArray = jsonObject.getJSONArray("routes");
To go through each array element (that are json objects) you iterate like this:
for (int i = 0; i < routesArray.length(); i++) {
//do sth
}
And you get your "legs" like this:
JSONObject routeObject = routesArray.get(i);
routeObject.get("legs");
And deeper and deeper like above.
Automatically
It's much easier to use Gson library and some Json Pojo parsers.
You import gson in your build.gradle:
compile 'com.google.code.gson:gson:2.4'
Than you can use this parser. Select source type "JSON" and "Annotation style" Gson. Put your json in text box and click Preview or download ZIP. You can also put your package name and main class name or rename it manually later. You will be given multiple model classes with top one called "Example" or your name. It consists of two fields:
public class Example {
#SerializedName("geocoded_waypoints")
#Expose
private List<GeocodedWaypoint> geocodedWaypoints = new ArrayList<GeocodedWaypoint>();
#SerializedName("routes")
#Expose
private List<Route> routes = new ArrayList<Route>();
Add all classes to your project and than you just parse your jsonString to your main class like this:
Example mainClassObject = new Gson().fromJson(jsonString, Example.class);
And now you can access routes from this object. And legs from routes and deeper and deeper...
Please try below code to parse provided json keys value :
private void parseJson(String jsonString){
ArrayList<String> legsDistanceList = new ArrayList<>();
ArrayList<String> legStepsDistanceList = new ArrayList<>();
try{
JSONObject rootJson = new JSONObject(jsonString);
if(rootJson.has("routes")) {
JSONArray routesJsonArray = rootJson.getJSONArray("routes");
for(int i=0;i<routesJsonArray.length();i++){
JSONObject routeJson = routesJsonArray.getJSONObject(i);
if(routeJson.has("legs")){
JSONArray legsJsonArray = routeJson.getJSONArray("legs");
for(int j=0;j<legsJsonArray.length();j++){
JSONObject legJson = legsJsonArray.getJSONObject(j);
if(legJson.has("distance")){
JSONObject distanceJson = legJson.getJSONObject("distance");
legsDistanceList.add(distanceJson.getString("text"));
}
if(legJson.has("steps")){
JSONArray stepsJsonArray = legJson.getJSONArray("steps");
for(int k=0;k<stepsJsonArray.length();k++){
JSONObject stepJson = stepsJsonArray.getJSONObject(k);
if(stepJson.has("distance")){
JSONObject stepDistanceJson = stepJson.getJSONObject("distance");
legStepsDistanceList.add(stepDistanceJson.getString("text"));
}
}
}
}
}
}
}
}catch (Throwable e){
e.printStackTrace();
}
Log.i("Legs Distance ",legsDistanceList.toString());
Log.i("Legs Steps Distance ",legStepsDistanceList.toString());
}
I think above code might be difficult for you to understand at this stage but once you understand then it will more helpful to you for future JSON parsing stuff.
you can third parties(Gson, Logan Square,etc..) for parsing. If you are trying to access it directly. Below you can find the sample code to access the "legs" array.
Let us assume
JsonObject jsonObject = new JsonObject("json string");
this "jsonObject" is the full json value, from which you want to access the "legs" array. In this scenario the "legs" array is inside the "routes" array. So we need to get the "routes" array first and loop that array and get the "legs" array from each object and store in POJO class or if you want to fetch the "text" alone from the "distance" means you can store that in arraylist or string which you need. Below is the sample code to get the text alone.
JsonArray routesArray = jsonObject.optJsonArray("routes");
if (routesArray != null) {
for (int i = 0; i < routesArray.length(); i++) {
JsonArray legsArray = routesArray.get(i).optJsonArray("legs");
if (legsArray != null) {
for (int i = 0; i < legsArray.length(); i++) {
JsonObject legObject = legsArray.get(i);
JsonObject distanceObject = legObject.optJsonObject("distance");
String textValue = distanceObject.optString("text");
}
}
}
}
Hope this is helpful :)

Json parsing problems while using google api places

I am trying to parse some data from json file while using google api places i want to get the "names" only then save it in a list but i get json exception
here it's my file
{
"html_attributions" : [],
"next_page_token" : "ClRHAAAAyPJvpPTgNnOURBi9XhfVvw5J2Howz_h41h1HysWrYomdpQrRwMnWeKRKyiGU6ku6ZxxzQ3fLb598QgwyYYIF9PiK6ynAaBj-XOnbr7s2eTESEHTjEzwG8k6iwf3aFGTmeh0aFAH6KblOYgOw80zn7E-NgcdahjZl",
"results" : [
{
"geometry" : {
"location" : {
"lat" : 30.03735730,
"lng" : 31.2324840
},
"viewport" : {
"northeast" : {
"lat" : 30.04394240,
"lng" : 31.23577240
},
"southwest" : {
"lat" : 30.03077210,
"lng" : 31.22919559999999
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "b466d997e9c8b69f328895a42143f1da8b445e28",
"name" : "Garden City",
"reference" : "CqQBnAAAAHWLMK-4WmAwrZBlBfrSCs8ycrG7voN6sT-vFtqDUhVuxIVHJoAyA2JjVqzCSlJfJcI8DqUg1PFQUwQMDJvZinsx_-YJtYhr01Oa3wvj-CUvGR8m3WlxQEWUB0_tsm6mt5WDCEsMsnmhgRmgrOYmAMePGI_DndEBkOJjhqLoEo1VZblKaa730ZsBe1Wjp_NAYHm1reTeiHlBW5dMVhmCX7cSEAwbfJ3xpIJ_FUCoSlM-5hkaFM3vnuXUv1KVws2t-1L0CR8ldSRB",
"types" : [ "neighborhood", "political" ],
"vicinity" : "Cairo"
},
{
"geometry" : {
"location" : {
"lat" : 30.0429350,
"lng" : 31.2246040
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "710a28e1d1e2aefdd69ea6ec2e30fbfc9f5b54cb",
"name" : "Cairo Opera House",
"photos" : [
{
"height" : 478,
"html_attributions" : [ "From a Google User" ],
"photo_reference" : "CnRsAAAAJxKE7CfYmG89VEHODwClX4P3XbKD0h1j_xghhy0KvINsO9KMNWxkxq65xXPPXzZHWX104qjm3TTJaxh1mUeATTkRspBOVJll0JwZ-8fA_0DaXJ2RVr4pE7rPAKYkW9VE9qwIQ7ba_nvg5j7Nua96ihIQdEM9euo3M8jXH8CdpSj5ixoUq-W9Me_M9edgTscsjn5pBhnOTt8",
"width" : 613
}
],
"rating" : 4.50,
"reference" : "CoQBfAAAAD6AaWl7Ze1hxuelIZZkH8dD0VrsBBIpDOkfjwSItQ276DnGHiLYc4BEcPGyNuw_OPX7HfaPuIYFvN-ctpgcIV2tC5uw3nPP_Z4OTb5y0zD0CaelxZN3a-m0tBiqZHPylp7FpXOHERNc6BUInaWO3_h4Aze7M_FuOw21-zttSBvnEhBl62ERpUcU8nZIJy7DBrKuGhQn65AeXttY1axK8Qkvn7nKxDOuqA",
"types" : [ "establishment" ],
"vicinity" : "Opera Land, EL GEZIRAH"
},
{
"geometry" : {
"location" : {
"lat" : 30.0459720,
"lng" : 31.224110
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "fc80f712dc787d1c2c4382992e25895b8994bcdd",
"name" : "Cairo Tower",
"photos" : [
{
"height" : 1024,
"html_attributions" : [ "From a Google User" ],
"photo_reference" : "CnRoAAAAKUsL4sanCSNRjYRUSPbEbUoK73LuBWW36PuIAqebOTu3llxvJwtsQmtMpE_aqXjwtkZwjinZQqXWWd_8XQDGRtDPpKj5l97Jy02_zsT8KBLueOgaX4LlU0fAxKvQaM3SMJPehF2-x_qb0yn0Pbm4eRIQgX2VP1lXHnrefEKxk_NIshoUYZXYJAsB-z64TzWV4d6ACAxJqbo",
"width" : 768
}
],
i tried something like that
String data = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = new JSONObject(data);
Object jj=jsonObj.getJSONObject("results").get("name");
but i got JSONEXCEPTION
results is an array not an object:
JSONObject jsonObj = new JSONObject(data);
JSONArray results =jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String name = result.getString("name");
Log.d("tag", "name: " + name)
}
Don't have a compiler here so cannot check syntax.

how can i get an JSONObject from a json array

I am new to android programming and i would like to know how do i get a certain object from a JSONarray.
My JSON looks like this:
{"results" : [
{
"address_components" : [
{
"long_name" : "Contern",
"short_name" : "Contern",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Luxembourg",
"short_name" : "Luxembourg",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Luxembourg",
"short_name" : "LU",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Contern, Luxembourg",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 49.621830,
"lng" : 6.302790
},
"southwest" : {
"lat" : 49.56759010,
"lng" : 6.195380
}
},
"location" : {
"lat" : 49.58515930,
"lng" : 6.2274880
},
and i want to extract the lat and lng from location.
my code is:
arr = json.getJSONArray("results");
JSONObject location=arr.getJSONObject(4);
double lng = location.getDouble("lng");
double lat = location.getDouble("lat");
I wanted to say that your json file is wrong but after closer look I think your code is bad :) I suppose it doesn't give you want you want now.
"results" in this case is JsonArray - but an array of full JsonObjects, not it's properties!
Full JsonObject is object with - address_components, format_address, geometry etc. "location" is also a part of "geometry" object.
When you are sure there will be only one object in "result" array - you can do:
arr = json.getJSONArray("results");
if (arr.length() > 0){
JSONObject resultObject = arr.getJSONObject(0);
JSONObject geometry = resultObject.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
double lng = location.getDouble("lng");
double lat = location.getDouble("lat");
}
When you have more than 1 object in result - I suppose you need to loop over them and find what you need.
Hello Refer below code
JSON String
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}

Categories

Resources