Spring @ResponseBody返回JSON,但是缺少键 [英] Spring @ResponseBody returns JSON, but keys are missing

查看:89
本文介绍了Spring @ResponseBody返回JSON,但是缺少键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以JSON格式返回SQL查询的结果.结果还可以,但是缺少键(查询中指定的列).是否必须将类与查询关联才能获得键名?我不认为这是杰克逊映射,因为当我明确使用它(对象映射器而不是让Spring在@ResponseBody中处理它)时,我得到相同的结果.

I'm returning the results of a SQL query in JSON format. The result is ok, but the keys (columns specified in the query) are missing. Do I have to associate a class with the query in order to get key names? I don't think it's the Jackson Mapping since when I use it explicitly (object mapper instead of letting Spring handle it in the @ResponseBody) I get the same result.

Spring 3.2.1,Hibernate 3.6.使用Hibernate createSQLQuery从5个表中获取结果.

Spring 3.2.1, Hibernate 3.6. Using Hibernate createSQLQuery to get results from 5 tables.

List<EvalMasterEvalDetail> details = session.createSQLQuery(query).list();

结果如下:

[[61,"Conference","CME Conference"],[42,"Lecture","fellow lecture"]]

应该是

[[{"detail_id":61, "event_type":"Conference", "event_name":"CME Conference"}],
[{"detail_id":42, "event_type":"Lecture", "event_name":"fellow lecture"}]]

推荐答案

默认情况下,Hibernate中的SQL查询返回标量值的列表(对于select中的单列)或Object[]列表(对于多列)

By default SQL query in Hibernate returns a list of scalar values (for single column in select) or a list of Object[] (for multiple columns).

您有后一种情况.在这种情况下,List<EvalMasterEvalDetail>并不意味着列表包含EvalMasterEvalDetail的实例,因为list()返回原始的List,因此您可以进行未经检查的转换.

You have the latter case. List<EvalMasterEvalDetail> in this case doesn't mean that list contains instances of EvalMasterEvalDetail, because list() returns a raw List, so that you have unchecked conversion.

如果每个结果元组代表一个映射的实体(或多个映射的实体),则可以使用

If each tuple of result represents a mapped entity (or multiple mapped entities), you can use addEntity() and addJoin() to convert them to entities.

如果每个结果元组都表示一个任意(未映射)类,则可以使用ResultTransformer(例如

If each tuple of result represents an arbitrary (non-mapped) class, you can use ResultTransformer (such as AliasToBeanResultTransformer).

您还可以手动将Object[]转换为目标对象(在复杂情况下很有用).

Also you can convert Object[]s to target objects manually (useful in complex cases).

这篇关于Spring @ResponseBody返回JSON,但是缺少键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆