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")
Related
Can someone help me in extracting the JSON response? I want to fetch the value for asset and ID and name under client and assert it in my code. Nothing is working for me to extract these values in my java code
[
{
"metadata": {
"asset": "ef59872625",
"customerInfo": {
"client": {
"id": "0CgIHVIA3",
"name": "JAssociates"
}
},
"adInfo": {
"title": "Te1",
"adId": "Te1",
"cartNumber": "98462",
"dueDate": "2021-06-23",
"dubber": {
"id": null,
"name": null,
"email": null
},
"archiveOn": "2021-06-29",
"eraseOn": "2021-09-24",
"length": {
"unit": "seconds",
"amount": 30
},
"creatID": 15813794
},
"targetInfo": [
{
"channelType": "AA",
"market": {
"id": 400,
"name": "Dallas, TX",
"Status": "Success",
"Status2": {
"state": "Submitted",
"message": null
}
}
}
]
},
"links": [
{
"href": "https://interntadata",
"type": "metadata"
},
{
"href": "https://interntent",
"type": "content"
}
]
}
]
Any pointers It would be a great help
1) First, get the response body by hitting the URL.
Response resp = RestAssured.given().headers("Content-Type", ContentType.JSON, "Accept", ContentType.JSON).
when().get("{{YOUR-URL}}").
then().contentType(ContentType.JSON).extract().response();
String responseBody = resp.getBody().asString();
2) Extract Value from JSON:
First Method: Using JsonPath
import io.restassured.path.json.JsonPath;
JsonPath js = new JsonPath(responseBody);
String asset = js.getString("metadata.asset");
System.out.println(asset);
String id = js.getString("metadata.customerInfo.client.id");
System.out.println(id);
String name = js.getString("metadata.customerInfo.client.name");
System.out.println(name);
Second Method:
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray object = new JSONArray(responseBody);
JSONObject metadataObj = ((JSONObject)object.get(0)).getJSONObject("metadata");
String asset = metadataObj.getString("asset");
System.out.println(asset);
JSONObject customerInfoObject = metadataObj.getJSONObject("customerInfo");
JSONObject clientObject = customerInfoObject.getJSONObject("client");
String id = clientObject.getString("id");
System.out.println(id);
String name = clientObject.getString("name");
System.out.println(name);
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>LATEST</version>
</dependency>
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");
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);
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);
}
I'm working on Facebook Scores API for an android app. I query for the user score by accessing the user graph:
https://graph.facebook.com/user_id/scores&access_token={user_access_token}
I get a response like:
{
"data": [
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1200,
"application": {
"name": "QuizzlePeople",
"namespace": "quizzlepeople",
"id": "176694722487191"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1,
"application": {
"name": "Friend Smash!",
"namespace": "friendsmashsample",
"id": "480369938658210"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "Wordox",
"namespace": "wordox-the-game",
"id": "227993680602156"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "SongPop",
"namespace": "songpop",
"id": "323595464361460"
}
}
]
}
How do I extract useful data from this?
I'm trying to take something as a JSONObject, using:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/me?fields=score&access_token=" + token);
HttpResponse resp = client.execute(get);
Log.i("info1", resp.toString());
// Parse the response
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
Log.i("info1", response);
JSONObject result = new JSONObject(response);
JSONArray arr = result.getJSONArray("data");
Log.i("info2", arr.toString());
just to see if I can take anything, say, the array named 'data'. Yet the logcat does not show me anything. It shows the first 2 logs, but not the 3rd. Any ideas?
That looks like JSONObject. You can loop thru it and do whatever you wish with the data.
Have a look at http://json.org/ for documentation for a specific language (I presume you need java so click on the java link).
I appended the data to a table to give you an idea ( jquery / javascript ):
fiddle:http://jsfiddle.net/H8LNB/4/