【问题标题】:Convert List<object> to JSON将 List<object> 转换为 JSON
【发布时间】:2019-05-08 07:36:11
【问题描述】:

我正在使用 spring data jpa 从数据库中获取数据。我在存储库接口中为此编写了代码。但是我得到了以下格式的 jpql 输出:

[[21632,"Allfrey Laboratory","110060"],[21633,"Allis Laboratory","110070"]

但我想要这个 json 格式的输出,例如:

[{"ndept_id":21632,"sdept_name":"Allfrey Laboratory","ninst_id":60,"bis_locked":false,"sclient_dept_id":"110060","nsurvey_method_id":1,"bis_jointuse":false,"ntemp_dept_id":4,"balternate_jointuse_percentage":false,"ndiv_id":null}]

DepartmentRespository

@Repository
public interface DepartmentsRepository extends JpaRepository<Department, Integer> 
{
    @Query("select d.ndept_id,d.sdept_name,d.sclient_dept_id from Department d")
    public List<Department> findColumns();
}

部门控制器

 @RequestMapping(value="/findcolumn", method=RequestMethod.GET)
    @ResponseBody
    public List <Department> findColumnData()
    {
        return departmentservice.getColumns();
    }

【问题讨论】:

  • 这个 jpql 输出来自哪里?这是部门toString 方法的结果吗?向我们展示您的Department 课程的代码。如果我理解正确,您只需要创建一个包含所需字段的 DepartmentDTO 并将其返回到 Controller(而不是返回 Department)。

标签: spring-data-jpa jpql


【解决方案1】:

我正在使用 spring data jpa 来获取数据库数据。为此,我在存储库接口中使用了 jpa 查询。通过使用上述查询,我​​无法以正确的格式获取获取的输出。我想要 json 格式的输出。 为此,我在选择语句中添加了new map。我解决了我的错误。

更新:

@Repository
    public interface DepartmentsRepository extends JpaRepository<Department, Integer> 
    {
        @Query("select new map(d.ndept_id,d.sdept_name,d.sclient_dept_id) from Department d")
        public List<Department> findColumns();
    }

【讨论】:

    猜你喜欢
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多