我以这种方式定义了namedQuery
@NamedQuery(name = "Emp.findAll",
query = " select new test.entity.Emp(o.empNo, o.salary, p.projectId, p.projectName)
from Emp o inner join o.project p ")
在服务类中,我有
@GET
@Path("/projects")
@Produces(MediaType.APPLICATION_JSON)
public List<Emp> findAll() {
return this.queryFindAll();
生成的JSON就是这种格式
[{"empNo":"2390","empName":"JAMES","projects":{"projectId":209,"projectName":"Z560"}}]
理想情况下,我想以下列格式生成JSON
[{"empNo":"2390","empName":"JAMES","projectId":"209","projectName":"Z560"}]
我该怎么做?
更新1
@GET
@Path("/projects")
@Produces(MediaType.APPLICATION_JSON)
public Object findAll() throws IOException{
String empAsJson = null;
List<Emp> list = queryFindAll();
ObjectMapper objectMapper = new ObjectMapper();
empAsJson = objectMapper.writeValueAsString(list);
return empAsJson;
}
答案 0 :(得分:1)
看起来项目被序列化为地图/对象,你只需要将它作为地图或对象的数组。
使用伪代码更新:
List<Map<String,String>> rolledupEmps = new ArrayList<Map<String,String>>();
for(Emp emp : emps){
Map<String,String> em = mapper.readValue(emp, HashMap.class);
em.put("projectId",em.get("projects")?!=null:em.get("projects").get("projectId"),"");
em.put("projectName",em.get("projects")?!=null:em.get("projects").get("projectName"),"");
em.remove(""projects"");
rolledupEmps.put(em);
}
return mapper.writeValueAsString(rolledupEmps);