我有json响应如下
[{"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}]}]
我想要一个像这样的json而不是上面的格式
[{"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投影中检索子组时,结果将删除sum值并返回单个值
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);
hibernate查询是,
db.collection.find().sort({team:1}).exec(fn)
我使用Spring启动应用程序和带有java 1.8版本的postgresql数据库
答案 0 :(得分:1)
如果你想获得你想要的json结果,你应该创建一个自定义DTO,请参阅下面的例子。
class Child {
String sub;
Long amount;
}
class Dto {
String name;
Long totalAmount;
List<Child> child;
}
然后组成你的Dto并添加必要的孩子。下面是示例,假设您已经拥有db:
的结果如果您的回报是List<Child>
,那么您可以这样做..
Dto dto = new Dto();
dto.addAll(rs);
dto.setName("name");
dto.setTotalAmount(totalAmount);
return dto;
如果rs结果不是List<Child>
,你可以这样做......
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;
有效的结果JSON如下所示:
{
"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
}
]
}