I am new to android json i want put the req and get the response from the google matrix api server in android i want send the req :
http://maps.googleapis.com/maps/api/distancematrix/json?origins=Hyderabad,Andhra%20Pradesh,India&destinations=Eluru,Andhra%20pradesh,India&mode=driving&language=fr-FR&sensor=false
and that url returs the output is as fallows i want extract the km value from that result. :
{
"destination_addresses" : [ "Eluru, Andhra Pradesh, Inde" ],
"origin_addresses" : [ "Hyderabad, Andhra Pradesh, Inde" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "330 km",
"value" : 330316
},
"duration" : {
"text" : "5 heures 1 minute",
"value" : 18052
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
How to get the distance value and print in the app console?
In the Following shown way you can retrieve the km from your JSON Output.
JSONObject jobj = new JSONObject(your result);
JSONObject json;
json = jobject;
JSONArray jrowsArray = json.getJSONArray("rows");
for(int i=0;i<jrowsArray.length;i++){
JSONArray jElementsArray = jrowsArray.getJSONArray("elements");
for(int j=0;j<jElementsArray.length;j++){
JSONObject jDistance = jElementsArray.getJSONObject("distance");
String distancekm = jDistance.getString("text");
}
}
Related
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();
}
}
My json link to json
This is the code to fetch the items. I am getting the error while fetching the photo_reference. I know that photos is a JSONarray and inside that a JSONobject is there. The error is that it shows as no value for photos. how to get the array and how to fetch the photo_reference string? I'm new to JSON and this is quite difficult for me. Log cat is also shared. Thank you in advance.
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("results");
for (int i = 0; i<array.length();i++)
{
//get the photo reference from json of google place web api
JSONObject o = array.getJSONObject(i);
Places item = new Places();
JSONArray photo = o.getJSONArray("photos");
JSONObject photos = photo.getJSONObject(0);
String ph_ref = photos.getString("photo_reference");
String id = o.getString("id");
String name = o.getString("name");
if (o.has("rating")) {
String rat = o.getString("rating");
item.setRating(rat);
}else{
item.setRating("0");
}
org.json.JSONException: No value for photos
Logcat
org.json.JSONException: No value for photos
at org.json.JSONObject.get(JSONObject.java:389)
at org.json.JSONObject.getJSONArray(JSONObject.java:584)
UPDATE
MY SOLUTION
if (o.has("photos")){
JSONArray photo = o.getJSONArray("photos");
JSONObject photos = photo.getJSONObject(0);
String ph_ref = photos.getString("photo_reference");
item.setPh_ref(ph_ref);
}
else
item.setPh_ref("no photos available");
Some items doesn't have the photos object in the json.
So you need to check the photo object,
JSONArray photo = o.getJSONArray("photos");
if(photo != null) {
JSONObject photos = photo.getJSONObject(0);
}
Some of the items just don't have "photos" inside. One of them is:
{
"geometry" : {
"location" : {
"lat" : 26.1744046,
"lng" : 91.7769246
},
"viewport" : {
"northeast" : {
"lat" : 26.1757411802915,
"lng" : 91.7782234802915
},
"southwest" : {
"lat" : 26.1730432197085,
"lng" : 91.77552551970849
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/lodging-71.png",
"id" : "f66820fca7c21cb6783fe27a996af3379ed7140e",
"name" : "OYO 5332 Parnil Palace",
"place_id" : "ChIJ0S48-Z5ZWjcRBXSBd8gS9q4",
"rating" : 4.5,
"reference" : "CmRSAAAAlzfMwWtNWJb8fFFyzsqNBxyZgbfbR4IPZLP2qQVph1NBgZqEwolpKNc7rRXBAQVFX4ph31iYvCrFM77v5QqDY8gEIWHBJMdW9vqWSiMlDCDF-_r6N4AUviMXwH6xTq64EhAFOGo0wihXKEy8GPtQayxiGhS6SNxnJ6DI58p9uwhSek-ov2pLJA",
"scope" : "GOOGLE",
"types" : [ "lodging", "point_of_interest", "establishment" ],
"vicinity" : "Zoo Road, Zoo Tiniali, Guwahati"
},
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 :)
in this example, i like to know which city is closer to Vancouver. Victoria , Washington or Texas? one I find shortest distance how can I see which destination_address this value belong to?
{
"destination_addresses" : [
"Victoria, BC, Canada",
"Texas, États-Unis",
"Washington, District de Columbia, États-Unis"
],
"origin_addresses" : [ "Vancouver, BC, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "135 km",
"value" : 134638
},
"duration" : {
"text" : "6 heures 37 minutes",
"value" : 23815
},
"status" : "OK"
},
{
"distance" : {
"text" : "3 457 km",
"value" : 3456694
},
"duration" : {
"text" : "7 jours 15 heures",
"value" : 658855
},
"status" : "OK"
},
{
"distance" : {
"text" : "5 000 km",
"value" : 4999636
},
"duration" : {
"text" : "11 jours 2 heures",
"value" : 956487
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I'm trying to find closest city to Vancouver by parsing the distance & find min distance. by finding that we see shortest distance belongs to Victoria. How canI say this min distance belongs to Victoria.
this is my code for finding closest city ( shortest distance)
public class MainActivity extends Activity {
HttpClient client;
double minDistance=0;
String destination_addresses;
JSONArray rows;
JSONArray elements;
final static String URL= "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false";
protected void OnCreate (Bundle savedInstanceState ){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
client = new DefaultHttpClient();
}
public JSONObject ClosestObject (String Origin) throws ClientProtocolException, IOException , JSONException {
StringBuilder url= new StringBuilder (URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray locations = new JSONArray(data);
for (int i=0; i< locations.length(); i++){
rows= (JSONArray) locations.getJSONObject(2).get("rows");
elements= (JSONArray) locations.getJSONObject(0).get("elements");
String Value= elements.getJSONObject(i).toString();
double distanceValue = Double.parseDouble(Value);
if ( distanceValue< minDistance){
minDistance= distanceValue;
}
}
}
By the code you have given you are getting the JSON from Google url so you should read the documentation of the API, you will definitely get your answer there.
EDIT: and if you want to traverse the JSON array you can use yourjsonarray.getJSONObject(index).getString("Distance").
Try it :)
JSONObject bigData = new JSONObject(data);
rows = bigData.getJSONArray("rows");
elements = rows.getJSONObject(0).getJSONArray("elements");
JSONObject ob = elements.getJSONObject(0);
String value = ob.getJSONObject("duration").getString("value");//or "distance"
minDistance = Double.parseDouble(value);
int index = 0;
for (int i = 1; i < elements.length(); i++) {
ob = elements.getJSONObject(i);
value = ob.getJSONObject("duration").getString("value");//or "distance"
double distanceValue = Double.parseDouble(value);
if (distanceValue < minDistance) {
minDistance = distanceValue;
index = i;
}
}
JSONArray closers = bigData.getJSONArray("destination_addresses");
String closer = closers.getString(index);
Log.d("closer", closer);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
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);
}