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);
Related
I have called a rest api from exsternal system using restTemplate. everything is work fine but when I get null in some of values (in example the footer value is null) it is always give jsonexception error
result api
{
"status": "success",
"data": {
"id": "22",
"organization_id": "33",
"name": "name_isf",
"language": "id",
"header": {
"format": "IMAGE",
"example": "#<Hashie::Mash header_handle=#<Hashie::Array [\"result_pic"]>>"
},
"body": "contenty for body",
"footer": null,
"buttons": [],
"status": "APPROVED",
"category": "PERSONAL_FINANCE_UPDATE"
}
}
every call api exsternal i always catch with jsonobject like below
JSONObject res2 = qontakService.getDetailTemplate();
then i will give that to the controller
JSONObject gabunganResult = new JSONObject();
gabunganResult.put("template", objectMapper.writeValueAsString(getDetail.get()));
gabunganResult.put("templateQontak", res2);
and the result error is
com.fasterxml.jackson.databind.JsonMappingException: Object is null (through reference chain: java.util.HashMap["details"]->net.sf.json.JSONObject["templateQontak"]->net.sf.json.JSONObject["data"]->net.sf.json.JSONObject["footer"]->net.sf.json.JSONNull["empty"])
how do I solve this problem ? thank you
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")
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");
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 want to create a JSON Object using String.
Example :
JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}
In order to create the above JSON I am using this.
String message;
JSONObject json = new JSONObject();
json.put("test1", "value1");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 0);
jsonObj.put("name", "testName");
json.put("test2", jsonObj);
message = json.toString();
System.out.println(message);
I want to know how can I create a JSON which has JSON Array in it.
Below is the sample JSON.
{
"name": "student",
"stu": {
"id": 0,
"batch": "batch#"
},
"course": [
{
"information": "test",
"id": "3",
"name": "course1"
}
],
"studentAddress": [
{
"additionalinfo": "test info",
"Address": [
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":36
}
],
"verified": true,
}
]
}
Thanks.
org.json.JSONArray may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
String jsonString = "{'element1':'value1','element2':{'id':0,'name':'testName'}}";
JsonObject jsonObject = (JsonObject) JsonParser.parseString(jsonString);
Underscore-java can create json from an object.
import com.github.underscore.U;
String message = U.objectBuilder()
.add("course", U.arrayBuilder()
.add(U.objectBuilder()
.add("id", 3)
.add("information", "test")
.add("name", "course1")
))
.add("name", "student")
.toJson();
System.out.println(message);
// {
// "course": [
// {
// "id": 3,
// "information": "test",
// "name": "course1"
// }
// ],
// "name": "student"
// }