how to iterate json on servlet - java

i have json like
{
"condition": "AND",
"rules": [{
"id": "BirthDate",
"field": "BirthDate",
"type": "date",
"input": "text",
"operator": "equal",
"value": "2016/04/13"
}]}
i just want to iterate it on servlet for that i create
public String getRuleList(){
String ruleList=this.get("rules");
return ruleList;
}
public String getcondition(){
return this.get("condition");
}
as getter setter when i send this json without using JSON.stringify i got the value of condition but unable to fetch rules.By using JSON.stringify i unable to fetch anything. please help..

rules is JSONArray and simple get returns an object. Try to get it with the json libraries custom method.
If you are using org.json try this
this.getJSONArray('rules')
Try to provide some more information such as the json library you are using, the output you got for this.get('rules') and how is this initialized for a much better answer

To solve above problem i do
result =JSON.stringify(result);
var json = JSON.parse(result);
var queryData={
rules:JSON.stringify(json.rules),
condition:JSON.stringify(json.condition)
};
console.log("result"+JSON.stringify(result));
if (!$.isEmptyObject(result)) {
var url = location.protocol + "//" + location.host +appContext+"?command=QueryBuilderServlet&action=getQueryJson";
$.ajax({
url:url,
type: "POST",
data:queryData,
dataType:'json',
});
thanks a lot for your help

Related

Get json object in Array based on key and value in Java

I have a Json body like the example below. I need to extract the value from a key that has another key with a specific value in an array. I am passing in a JsonNode with everything in the detail component of the message, I can easily extract from each level, however, I'm struggling with the array.
In this case, I need to extract the value of "value" (Police/Fire/Accident Report) from the object in the array which has a key/value pair of "name":"documentTitle". I understand this is a JSONArray, but I can't find a good example that shows me how to extract the values for an object in the array that contains a certain key/value pair, I don't think I can rely on getting the object in position [2] in the array as the same objects may not always be present in the additionalMetadata array.
Sample Json:
"sourceVersion": "1.0",
"eventId": "8d74b892-810a-47c3-882b-6e641fd509eb",
"clientRequestId": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"detail": {
"stack": "corona",
"visibilityIndicator": null,
"documentUid": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"additionalMetadata": [
{
"name": "lastModifiedDate",
"value": "2021-05-21T04:53:53Z"
},
{
"name": "documentName",
"value": "Police/Fire Report, 23850413, 2021-05-20 14:51:23"
},
{
"name": "documentTitle",
"value": "Police/Fire/Accident Report"
},
{
"name": "documentAuthor",
"value": "System Generated"
},
{
"name": "lastModifiedBy",
"value": "System Updated"
},
{
"name": "createdBy",
"value": "System Generated"
},
{
"name": "documentDescription",
"value": "Police/Fire Report received"
},
{
"name": "organizationCode",
"value": "Claims"
}
]
}
}```
Loop through the json array and extract the json object with name documentTitile. From that json object you can get the value
Well, either the JSON framework you're using supports this out of the box (check the documentation) or you could convert it manually to a map:
List<AdditionalMetadataEntry> additionalMetadata;
[...]
Map<String, String> additionalMetadataMap = additionalMetadata.stream().collect(Collectors.toMap(AdditionalMetadataEntry::getName, AdditionalMetadataEntry::getValue));
I was able to figure it out. I created a new node off the existing notificationBody JsonNode, then parsed through the metadata key/value pairs:
String docTitle = "";
JsonNode additionalMetadata = notificationBody.get("detail").get("additionalMetadata");
for (JsonNode node: additionalMetadata) {
String name = node.get("name").asText();
String value = node.get("value").asText();
if(name.equals("documentTitle")){
docTitle = value;
}
}

Parse array in JSON using JsonPath in Java

I am using jayway JsonPath library to parse the JSON using the path given. I am able to get the string value if I give the correct path. But I want to get the list of maps when I give the path if its an array. For example, I have a JSON like below:
{
"employees": {
"company": "Google",
"people": [{
"name": "John",
"age": 25,
"location": "zurich"
},
{
"name": "Peter",
"age": 27,
"location": "Lucerene"
}]
}
}
Below is the code I am using to parse the json.
if I give the path $.employees.people, I am getting the String, But I need to List of Maps. Below is the code I am using to Parse Json using jsonpath.
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath) //But this is returning String
Anyone suggest proper approach to get what I expected.
try using,
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people[?]");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath);
if you need more details. readmore...

Get all records from JSON response

I'm still kind of new to the Rest Assured API world. I've read through as much documentation on https://github.com/rest-assured/rest-assured/wiki/Usage#example-3---complex-parsing-and-validation as I can stand.
I have a response that looks like:
{
"StatusCode": 200,
"Result": [
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "Home",
"PhoneNumber": "9701234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile1",
"PhoneNumber": "2531234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile2",
"PhoneNumber": "8081234567",
}
]
}
I've been struggling with how to get just the first record's PhoneNumber.
String responseBody=
given()
.relaxedHTTPSValidation().contentType("application/json")
.param("api_key", api_key).
when()
.get("/api/employees/" + employeeId)
.andReturn().asString();
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result");
phoneNumber = jsonPath.getString("PhoneNumber");
I get all the phone numbers in this case:
phoneNumber = "[9701234567,2531234567,8081234567]"
How can I get just the first record? I'd rather not have to perform string operations to deal with the, "[".
Thanks
You can simply do,
JSONObject json = new JSONObject(responseBody);
phoneNumber = json.getJSONArray("Result").getJSONObject(0).getString("PhoneNumber");
Here, 0 indicates the first record in the JSON Array Result.
Because you know the index of the element you want to retrieve, you can use the following code:
JsonPath jsonPath = new JsonPath(response);
String phoneNumber = jsonPath.getString("Result[0].PhoneNumber");

Separate each name-value pair in a JSON string to separate lines in a java string

I have a Java Spring MVC Web Application. I am trying to implement a form submission where the user will be submitting the form and an email would be sent to the user with the form data. I will receive the form data as JSON string. But the email sent with this data doesn't look readable. I have tried the following code to make the data more readable, but doesn't seem to make much difference:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonData);
String message = gson.toJson(je);
My JSON String looks something like below:
[ { "name": "FirstName", "value": "Abcd" }, { "name": "LastName", "value": "Efgh" }, { "name": "Email", "value": "test.mail#test.com" }, { "name": "PhoneNumber", "value": "9876543210" }, { "name": "Selected Locations", "value": " loc1, loc2, loc3" }, { "name": "Message", "value": "Hi" }, { "name": "g-recaptcha-response", "value": "03AMPJSYULxjYiDRiNxcOSVYxXR9F8dX5pqIYAZ6_F2igAwGvanS4Vh1Lm47ByS2qGELQ9W1h" } ]
I am looking for an option at least to bring name-value pair into separate lines so that it is in some readable manner when received through an email. Is there any way to do this. The form can be generic, SO I may not be able to map this string to any Java object.
I have already tried the following link and the solution does not work for me:
Pretty-Print JSON in Java
I also don't see many helpful details online regarding this. I am trying to put each name-value pair in a new line of the generated string to send the data as email.

Iterating Json Object in Jquery?

I want to know how to iterate a JSON object using jQuery. My requirement is I am getting a list from a Java Servlet to the UI and I have to populate a combo box with the AJAX response.
The above tack I already did it using struts2 and jQuery. Now I am in the middle of nowhere, how to iterate the Java List back in JSP:
$("#XXX option").remove();
$.each(data.YYYList, function(index, item) {
$("#XXX").append($("<option></option>").text(item).val(item));
});
I have set the MIME type as response.setContentType("application/json");
Can any one please guide me how to achieve this. Please let me know if any other information is needed from me.
Based on the small amount of information given by Esh, here is an example that I created for the very function you listed. I have a JSON that I want to be used in multiple select boxes.
Fiddle
Example Json:
"yyyList": [
{
"Id": "1",
"Name": "aaaa "
}, {
"Id": "2",
"Name": "bbb "
}, {
"Id": "6",
"Name": "ccc "
}, {
"Id": "7",
"Name": "ddd "
} ]
$.ajax({
url: "URL",
//data: "",
type: "GET",
dataType: 'json',
success: function (data) {
$.each(data.YYYList, function () {
$('#state').append('<'option value='+this.Id+'>'+this.Name+'<'option>');
});
}
})
$('#state') ---> gives the same id for select tag in HTML
Please make correct it option syntax
Hope this helps.

Categories