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");
Related
I have a JSON schema class that is auto generate using AVRO. I would like to create a GSON object using this JSON. I try to do so using this code
#Test
public void parseJson() {
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("/pathto/test.json"));
ThinEvent thinEvent = new Gson().fromJson(jsonObject.toString(), ThinEvent.class);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
but this results in the following error ... It looks like GSON is looking for a string but the json actually contains a nested object? The ThinEvent object has refService declared as a list.
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 74 path $.references[0].refService
private java.util.List<com.lm.gde.eventing.avro.Reference> references;
Here is my JSON, I have replaced some values with XXXX.
{
"eventType": "policy.PolicyPremiumChangedEvent",
"correlationId": "XXXX",
"references": [
{
"ref": "XXX",
"refType": "policy_id",
"refService": {
"com.lm.gde.eventing.avro.RefService": "policy_service"
},
"links": {
"array": [
{
"refUri": ""
}
]
}
},
{
"ref": "XXXXXX",
"refType": "policy_number",
"refService": {
"com.lm.gde.eventing.avro.RefService": "policy_service"
},
"links": {
"array": [
{
"refUri": "XXXXXX"
}
]
}
},
{
"ref": "2019-09-28",
"refType": "policy_tx_effective_date",
"refService": {
"com.lm.gde.eventing.avro.RefService": "policy_service"
},
"links": {
"array": [
{
"refUri": "XXXXX"
}
]
}
}
],
"eventContext": null,
"Timestamp": 1569574003295,
"Version": "1"
}
GSON supports nested objects check this article. Just create model that matches the Json (but in Java/Kotlin) and toss it to GSON. Same with collections. You can even use List instead of arrays.
You could just get the json file as a complete string and deserialize that as well.
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 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 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"
// }