Reputation: 13
I have json response like below
[{"Name":"kannur hub","Amount":1840.00},{"Name":"Calicut Hub","Amount":7000.00}]
i want a json like this instead of the above format
[{"name":"kannur hub","TotalAmount":1840,"child":[{"sub":"Sale Of Products @ 12 % Tax","amount":345,"sub":"sos","amount":1020,"sub":"Boss","amount":475}]},{"name":"Calicut Hub","TotalAmount":7000,"child":[{sub":"cop","amount":3500,"sub":"SALES ACCOUNT","amount":3500}]}]
So whenever i retrieve children grouping from hibernate projections,the result removes the sum value and return individual values
[{"sub":"Boss","Name":"kannur hub","Amount":475.00},{"sub":"sos","Name":"kannur hub","Amount":1020.00},{"sub":"cop","Name":"Calicut Hub","Amount":3500.00},{"sub":"SALES ACCOUNT","Name":"Calicut Hub","Amount":3500.00},{"sub":"Sale Of Products @ 12 % Tax","Name":"kannur hub","Amount":345.00}]
hibernate query is,
ProjectionList proj = Projections.projectionList();
proj.add(Projections.groupProperty("offId.officeProfileName").as("Name"));
proj.add(Projections.groupProperty("accId.accHeadName").as("sub"));
proj.add(Projections.sum("accountsDataValue").as("Amount"));
crit.setProjection(proj);
Iam using spring boot application and postgresql database with java 1.8 version
Upvotes: 1
Views: 824
Reputation: 716
You should create a custom DTO if you want to achieve the json results you want, please see example below.
class Child {
String sub;
Long amount;
}
class Dto {
String name;
Long totalAmount;
List<Child> child;
}
then compose your Dto and add necessary children. Below are the example, assumed that you already have the results from db:
if your rs return is List<Child>
then you can do this..
Dto dto = new Dto();
dto.addAll(rs);
dto.setName("name");
dto.setTotalAmount(totalAmount);
return dto;
or if rs result is not List<Child>
you can do this...
Dto dto = new Dto();
//assumed rs contains the db child results.
for(int i=0; i<rs.length; i++) {
Child child = new Child(rs.get("sub"), rs.get("amount"))
dto.getChild().add(child)
}
dto.setName("name");
dto.setTotalAmount(totalAmount);
return dto;
The valid resulting JSON is like below:
{
"name":"kannur hub",
"TotalAmount":1840,
"child":[
{
"sub":"Sale Of Products @ 12 % Tax",
"amount":345,
},
{
"sub":"sos",
"amount":1020,
},
{
"sub":"Boss",
"amount":475
}
]
},
{
"name":"Calicut Hub",
"TotalAmount":7000,
"child":[
{
"sub":"cop",
"amount":3500
},
{
"sub":"SALES ACCOUNT",
"amount":3500
}
]
}
Upvotes: 1