angular 6 array to JSON for spring backend - java

I have a Java backend that accepts a json response like this:
{
"accounts": [{
"t1_Title": "title1"
}, {
"t1_Title": "title2"
}]
}
In Angular i send an array to a service to be sent to the backend.
How do i add "accounts" to an array and keep the structure above from the array which is structured like this:
(2) [Array(1), Array(1)]
0: [{…}]
1: [{…}]
length: 2

Simply bind the array value to accounts key within a new object.
Example code :
let myArray = [{ "t1_Title": "title1" }, { "t1_Title": "title2" }]
//build JSON
let obj = {accounts : myArray};
// print JSON
console.log(obj)

Related

JSON parsing help (Native Android, java)

I am trying to do JSON parsing. The JSON data is shown below, I am trying to get the "categories". I was able to JSON parse everything else, but I am not sure what does this "categories" belong to, is it a JSONObject, JSONArray, or something else? I am a newbie and self-taught, usually I am familiar that JSONArray has form of "JSONArray": {["content"]}, and the "content" is JSONObject. But in this case, "categories":["content"]. I am trying to parse this "categories", and turn it to string. Thank you for your help.
{
"results": [
{
"type": "Restaurant",
"id": "jfhuiewjkfkdljiahueijkfnlsdiejkl1484391hjk8421k",
"score": 99.9844207764,
"dist": 15.581982823437135,
"info": "search:ta:840369014527642-US",
"poi": {
"name": "RoofTop Bar",
"categorySet": [
{
"id": 184729472943
}
],
"categories": [
"pub food",
"restaurant"
]}
}]
}
This is what I have tried:
groups = new JSONArray();
groups = response.getJSONArray("results");
if (groups.length() > 0) {
JSONObject resultObject = groups.getJSONObject(0);
if (resultObject.has("poi")) {
if (resultObject.getJSONObject("poi").has("name")) {
nameResult = resultObject.getJSONObject("poi").getString("name");
} else {
nameResult = "Information is not available.";
}
if (resultObject.getJSONObject("poi").has("categories")) {
JSONObject categoriesResult;
categoriesResult = resultObject.getJSONObject("categories").toString();
}
results is an array of objects
The first object contains a property called poi
poi contains a property called categories
So using the top to bottom approach, we can arrive at
const categoriesArray = results[0].poi.categories; // gives categories as an array of strings
const categoriesString = categoriesArray.join(",") // gives categories as string, with comma separated values
I am not sure if it is the actual raw data but the poi object where the categories are contained is malformed. It is missing a closing bracket which could be causing parsing issues.
That apart, the field categories from the poi object is a list of strings I am not sure how you want to format it to a string but you could loop through them and do want you want with them.
In order to obtain them you can access them from your object with results[0].poi.categories or loop through the results before accessing the categories with result.poi.categories where result is the variable containing the currently looped result.
EDIT:
From your code sample, assuming response is a JSONObject you can do the following.
Then to obtain categories in a string without the array format, you can loop through the categories and concatenate them to a string.
String categories = resultObject.get("categories").join(", ");

not able to create Java Object from Json having double quote in value

I have same query. My JSON is as below.
String json="{ "credentials": { "password": "Password"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
key = password and value is "Password"123" it contains " (double quote).. I am not able to create a java object from this json as it is invalidated.
Gson gson = new Gson();
gson.fromJson(json, PasswordResetDetails.java);
Above code snippet is not Working.
If you are doing this for learning / testing purpose all you need to do is escaping the double quote using :
String json="{ "credentials": { "password": "Password\"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
If this is a real scenario then I would like to suggest to change the source in order to make sure it provides valid JSON.
There are countless possibilities to check if your JSON is valid (JSON linting), here's one.

initiate a new datatable with data when a row is clicked in another datatable using Spring MVC for data generation

Basically I want to have two tables on one page. In table 1 I want to store information related to areas, and in table 2, I want to show staff information related to the area being clicked.
My backend uses Spring MVC to generate data.
Table 1 is initiated this way:
function createTable1() {
tableOne = $('#table').dataTable({
ajax: function (data, callback, settings) {
var param = {};
param.type = "3";
$.ajax({
type: "post",
url: '/area/getareainfo',
dataType: "json",
data: param,
success: function (result) {
if (result) {
var returnData = {};
returnData.data = result;
callback(returnData);
}
}
});
},
columns: [
{"data": "label"},
{"data": "value"},
{"data": "count" },
{"data": "count" },
{"data": "count"}
]
});
}
I have a piece of very similar code for creating table 2 that I don't know if it is going to work yet (except I have destroyoption set to true)
$('#table tbody').on('click', 'tr', function () {
createTable2();
});
My task is to write a controller that relay data for table 1 and table 2, connecting the data between table 1 and table 2 in some way, and have the two datatables shown and worked. How should I structure this? (I have zero experience writing Spring MVC, and ignorant how I should use ajax for getting table 2 data from table 1 information and the backend)
Thank you very much for any input!
No need to destroy Table 2, you can use table2.ajax.reload() instead!
Also, no need to connect data between table1 and table2. You can have separate Datatables definitions for the two tables and separate AJAX urls returning JSON for the two tables. For example, assuming that your JSON for table1 looks like this:
{
"data": [{
"label": "1",
"value": "2",
"count": "3"
},
{
"label": "11",
"value": "22",
"count": "33"
}
]
}
Then your second datatable initialization code can be as follows:
tableTwo = $('#table2').dataTable({
ajax: "/staff/getStaffInfoForArea?"+areaCode,
columns: [
//your columns
]
});
where "/staff/getStaffInfoForArea?" is your server side URL appended with areaCode request parameter, and areaCode is a global javascript variable. You will have to store the row clicked on information in your areaCode variable like below:
$('#table tbody').on('click', 'tr', function () {
var rowSelected = tableOne.row({selected: true}).data();
areaCode = rowSelected.label //assuming 'label' is the key which store your area specific info
tableTwo.ajax.reload();
});
On Spring MVC side, your Controller method to get you table 2 data can look like this:
#RequestMapping(value = "/staff/getStaffInfoForArea", method = RequestMethod.GET)
public #ResponseBody String getPaginatedSiteIdents(#RequestParam String areaCode) {
//put all your Java code to retrieve staff info for area here
//and return a JSON string with "data" array
}
Of course there are a lot of specifics you need to take care of here. Hope this gives you a starting point!

Parsing JSON object from service call Spring JAVA

I am getting the following response from some service call . I am trying to parse the JSON . I am actually new to JAVA and not sure about how to parse JSON objects returned from HTTP call . I am getting the following error :
org.json.JSONException: JSONArray initial value should be a string or collection or array.
at org.json.JSONArray.<init>(JSONArray.java:197) ~[json-20180813.jar!/:na]
Code :
Object resp = hiveApiClient.getEnrollmentSearchDetails(certificate, employeeId);
logger.info("response : " + resp);
JSONArray mainArray = new JSONArray(resp);
// The nested array is at the second position : 1
JSONArray nestedArray = mainArray.getJSONArray(1);
// the interesting main JSONObject is on the first position
// of the nested array : 0
JSONObject interestingJSONObject = nestedArray.getJSONObject(0);
logger.info("XXX :{}", interestingJSONObject);
String courseId = interestingJSONObject.getJSONObject("additionalData").getString("courseId");
logger.info("XXXX :{}",courseId);
return courseId;
Response :
[
"list", [{
"#type": "com.saba.services.calendar.CalendarElementDetail",
"eventType": "ILTCLASS",
"elementName": "Microservice Application Architecture",
"elementId": "class000000000013497",
"eventId": "timel000000000103609",
"ownerID": "emplo000000000096641",
"locationId": "locat000000000003165",
"locationName": "IND-Bangalore-Karnataka",
"additionalData": {
"#type": "map",
"locationTimeZone": "tzone000000000000042",
"eventID": "class000000000013497",
"locationName": "IND-Bangalore-Karnataka",
"locationId": "locat000000000003165",
"transcriptID": "ofapr000000002962367",
"registrationID": "regdw000000001766254",
"eventName": "Microservice Application Architecture",
"moduleID": "regmd000000002147176",
"courseID": "cours000000000031995"
},
"startDate": {
"#type": "com.saba.customtypes.DateWithLocale",
"date": 1538613000000,
"locale": "03-OCT-2018",
"timeInLocale": "8:30 PM",
"dateInUserTimeZone": "03-OCT-2018",
"timeInUserTimeZone": "5:30 PM",
"dateInCustomTimeZone": null,
"timeInCustomTimeZone": null,
"customTimeZoneDate": 0,
"timeInStandardFormat": "8:30 PM",
"dateInStandardFormat": "10/03/2018"
}
}]
]
Well first of all, your json is not valid because of this}:
["list" : /* something here but anyway, not the concern here */ ]
when it should have been
{"list" : /* something here but anyway not the concern here */}
I think your problem is with the understanding of how a JSON file works and what is a json object and a json array. Please correct your JSON input so that we can provide you with insights on how to retrieve the value you need.
Additionally, I would recommend you looking into Jackson lib for parsing JSON objects to JAVA POJOs directly really easily. The link is a great tutorial to get you started here. Furthermore, jackson is already included with Spring so that you literally have nothing to install.
Edit
I misread the JSON input : I saw a : after "list" instead of a ,.
So your JSON is a proper JSON but its a quite uncommon JSON as it is loosely typed and therefore cannot be that easily parsed with standard Jackson library for example. In fact, in the main array, a string is put together with a Json Object which is a very bad practice but that's not your fault as I suppose you are not responsible for the output of this HTTP call.
So how can you actually get your value ? Well let's describe the JSON, you've got here : a JSON array containing a String and another sub JSON array. You want to take some values from the very first JSON object inside the nested json array.
This one :
{
"#type": "com.saba.services.calendar.CalendarElementDetail",
"eventType": "ILTCLASS",
"elementName": "Microservice Application Architecture",
"elementId": "class000000000013497",
"eventId": "timel000000000103609",
"ownerID": "emplo000000000096641",
"locationId": "locat000000000003165",
"locationName": "IND-Bangalore-Karnataka",
"additionalData": {
"#type": "map",
"locationTimeZone": "tzone000000000000042",
"eventID": "class000000000013497",
"locationName": "IND-Bangalore-Karnataka",
"locationId": "locat000000000003165",
"transcriptID": "ofapr000000002962367",
"registrationID": "regdw000000001766254",
"eventName": "Microservice Application Architecture",
"moduleID": "regmd000000002147176",
"courseID": "cours000000000031995"
},
"startDate": {
"#type": "com.saba.customtypes.DateWithLocale",
"date": 1538613000000,
"locale": "03-OCT-2018",
"timeInLocale": "8:30 PM",
"dateInUserTimeZone": "03-OCT-2018",
"timeInUserTimeZone": "5:30 PM",
"dateInCustomTimeZone": null,
"timeInCustomTimeZone": null,
"customTimeZoneDate": 0,
"timeInStandardFormat": "8:30 PM",
"dateInStandardFormat": "10/03/2018"
}
}
The first task here is to gather this object. Let's suppose the nested json array is always in the second position after the string and that the JSON object you want is always at the first position of the nested array which might not be the case depending on your input JSON but this was not precised in your question.
JSONArray mainArray = new JSONArray(resp);
// The nested array is at the second position : 1
JSONArray nestedArray = mainArray.getJSONArray(1);
// the interesting main JSONObject is on the first position
// of the nested array : 0
JSONObject interestingJSONObject = nestedArray.getJSONObject(0);
So now we want "courseId" from "additionnalData" Json Object :
String courseId = interestingJSONObject.getJSONObject("additionalData").getString("courseId");
And there you go!

Rest-Assured: Grabbing a JSON response inside an Array

Lets say I have a JSON response that returns an array:
[
{
"username": "dude",
"id": 123456,
},
{
"username": "hello",
"id": 654321,
}
]
How would I grab an element in the array using using Rest-Assured? For example I would just want to grab the first element of the array and print it.
Use following code
given()
.when()
.get()
.then().extract().path() // or .extract().jsonpath()

Categories

Resources