get a value from a json object (Google map distance) - java

hello I'm trying t get the distance from a JSON object
{
"destination_addresses": [
"Rabat, Morocco"
],
"origin_addresses": [
"Marrakesh, Morocco"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "324 km",
"value": 323624
},
"duration": {
"text": "3 hours 24 mins",
"value": 12233
},
"status": "OK"
}
]
}
],
"status": "OK"
}
I succeeded to get the elements object but I can't get the distance
org.json.JSONException: No value for distance
at org.json.JSONObject.get(JSONObject.java:389)
at com.application.zarbagaskazay.colivoiturage.testMApsActivity$1.onResponse(testMApsActivity.java:66)
at com.application.zarbagaskazay.colivoiturage.testMApsActivity$1.onResponse(testMApsActivity.java:56)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
here is the code
public void onResponse(JSONObject response) {
try {
JSONArray rows = response.getJSONArray("rows");
JSONObject elements=rows.getJSONObject(0);
// JSONObject cc= elements.getJSONObject("distance");
System.out.println(elements.get("distance"));
button.setText(elements.get("distance").toString());
} catch (JSONException e) {
e.printStackTrace();
}

In my suggestion:
You can replace
System.out.println(elements.get("distance"));
with
System.out.println(elements.getJSONArray("elements").getJSONObject(0).getJSONObj
ect("distance"));
Above sop will print/extract "distance" json value.
{"text":"324 km","value":323624}
Hope it works at your end too!

JSONObject jsonObject = new JSONObject("YOUR RESPONSE STRING");
JSONArray jsonArray = jsonObject.getJsonArray("rows");
JSONArray jsonArray_elements =jsonArray.getJsonObject(0).getJsonArray("elements");
JSONObject jsonObject_distance =
jsonArray_elements.get(0).getJsonObject("distance");
String text = jsonObject_distance.getString("text");
String value = jsonObject_distance.getString("value");

Related

How to update Rest API request Body array

I am trying to automate one API using rest API JAVA. I have kept sample request json in one file and before passing that json I want to modify some values. New values are in Map.
For example I want to modify 'company' value to 'Microsoft'(which is in hashmap newInputs). Problem is my code is adding new 'company' at the top of body instead of updating it. How do i update specific values in Items array.
json body in file
{
"Items": [
{
"newValue": "Q3",
"company": "Test",
"oldValue": "Q2",
"Date": "2022-03-27"
}
]
}
What i want to pass to API
{
"Items": [
{
"newValue": "Q3",
"company": "Microsoft",
"oldValue": "Q2",
"Date": "2022-03-27"
}
]
}
What my code is passing
{
"company": "Microsoft",
"Items": [
{
"newValue": "Q3",
"company": "Test",
"oldValue": "Q2",
"Date": "2022-03-27"
}
]
}
My code
public static String createItem(Map<String, String> newInputs) {
JSONArray jsonArray = null;
JSONObject jsonObject;
try {
jsonArray = new JSONArray(new String(
Files.readAllBytes(Paths.get("src", "test", "resources", "Payloads", "testdata.json"))));
jsonObject = new JSONObject(jsonArray.get(0).toString());
for (String key : newInputs.keySet()) {
jsonObject.put(key, newInputs.get(key));
}
jsonArray.put(0, jsonObject);
}

How to get a child attribute from JSONObject Java

I have a problem in my code where I need to print a child attribute from a JSONObject. Actually, I want to have the attribute values in a JSONArray because of some purposes.
<--So far I did-->
String preStringSingle = responseSingle.body().string(); // has the JSONObject
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
System.out.println(resultsJArray1);
<--JSONObject-->
"status": true,
"locale": "en-US",
"error_code": null,
"message": "OK",
"data": [
{
"service_list_access_mode": 0,
"service_list_domain": "http://www.hotsalesmarket.com",
"service_list_auth_method": 0,
"service_list_auth_user": null,
"service_list_auth_password": null,
"http_method": "GET",
"map_service_lists": [
{
"path": "sdfm.assets/assets/cameras/5799.jpg",
"service_item_id": 5799
},
{
"path": "dsf.assets/assets/cameras/5798.jpg",
"service_item_id": 5798
},
{
"path": "sdfsdf.assets/assets/cameras/6701.jpg",
"service_item_id": 6701
}
]
}
],
"timestamp": "2017-06-20T03:46:38Z"
}
I wanted to get all the details in the child attribute "map_service_lists".
<--Desired output-->
{
"path": "sdfsdf.assets/assets/cameras/5799.jpg",
"service_item_id": 5799
},
{
"path": "/sdfsdfs.assets/assets/cameras/5798.jpg",
"service_item_id": 5798
},
{
"path": "/sdfsdf.assets/assets/cameras/6701.jpg",
"service_item_id": 6701
}
You just have to continue like you did, but additional level down the hierarchy:
JSONArray data = resultsJObject.optJSONArray("data");
JSONObject firstData = data.optJSONObject(0);
JSONArray services = firstData.optJSONArray("map_service_lists");
System.out.println(services);
(Remove the array brackets from the result if you don't want them).
String preStringSingle = responseSingle.body().string();
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
JSONObject j = new JSONObject(resultsJArray1.get(0).toString());
JSONArray resultsJArray2 = j.optJSONArray("map_service_lists");
System.out.println(resultsJArray2);

Retrieve value Json field

I know that we have a lot of document on that but in my case I can't apply it.. I have a JSON file like that :
{
"Status": {
"Code": 0,
"Message": "Search OK"
},
"Applications": {
"Application": [{
"Id": 123,
"Name": "Bob"
},
...
]
}
}
I want to retrieve the value of the field "Name".
My code :
String jsonData = readFile("test.json");
JSONObject jobj = new JSONObject(jsonData);
JSONObject jobj2 = (JSONObject) jobj.get("Applications");
JSONArray jarr = new JSONArray(jobj2.getJSONArray("Application").toString());
After that I don't know what to do.. How can I resolve my problem?
Thanks a lot.
For this json:
{
"Status": {
"Code": 0,
"Message": "Search OK"
},
"Applications": {
"Application": [{
"Id": 123,
"Name": "Bob"
}]
}
}
Your code can looks like:
jsonObject
.getJSONObject("Applications")
.getJSONArray("Application")
.getJSONObject(0)
.getString("Name")

Add a new property to a specific json node using gson

I am exploring gson and wanted to check if I can remove and add elements. I have the below json
{
"header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321ef660",
},
"body": {
"search": {
"searchId": 9206422282,
"DateFrom": "2016-04-15T00:00:00-07:00",
"DateTo": "2016-06-24T00:00:00-07:00"
}
},
"amount": [
{
"amount": 73.704285,
"currency": "USD"
},
"amountagain": {
"amount": 96.791435,
"currency": "USD"
},
"winners": null,
"pgoodId": null,
},
and now I want to add a new element under body like :
{
"header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321c5690-1d2e-4403-9c31-029cc47ef660",
},
"body": {
"search": {
"searchId": 9206422282,
"DateFrom": "2016-04-15T00:00:00-07:00",
"DateTo": "2016-06-24T00:00:00-07:00"
"AddANewFieldHere" : **"2016-04-18"**
}
}
when I do
JsonObject jsonObject = new JsonObject();
try {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader("src/main/resources/search.json"));
jsonObject = jsonElement.getAsJsonObject();
} catch (FileNotFoundException e) {
} catch (IOException ioe){
}
// jsonObject.get("checkin");
jsonObject.addProperty("AddANewFieldHere","2016-04-18");
System.out.print(jsonObject);
}
It adds this property at the end of the document not as I expect under body.
jsonObject is the root node. You need to navigate to the node you want to modify.
JsonObject body = jsonObject.getAsJsonObject("body");
body.addProperty("AddANewFieldHere","2016-04-18");
From the example output, it looks like want it under the path body/search/searchId not body though:
JsonObject searchId = jsonObject
.getAsJsonObject("body")
.getAsJsonObject("search")
.getAsJsonObject("searchId");
searchId.addProperty("AddANewFieldHere","2016-04-18");

how to parse this in android with json

I want to parse this json in android. Can you help me how to parse, if i need to start from head to parse or from results for this I don't know. Can you help me
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Okay, first of all the JSON string you've given is invalid. I've written my answer based on the correct version of the JSON string that you have provided
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Now, to get the "values", you'll need to do this.
JSONObject jsonObject = new JSONObject(response);
JSONObject results = jsonObject.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
for (int i = 0; i < bindings.length(); i++) {
JSONObject binding = bindings.getJSONObject(i);
JSONObject city = binding.getJSONObject("city");
// Get value in city
String cityValue = city.getString("value");
Log.d("CITY", cityValue);
JSONObject country = binding.getJSONObject("country");
// Get value in country
String countryValue = country.getString("value");
Log.d("COUNTRY", countryValue);
}

Categories