如何使Spring Boot的GET返回JSON

时间:2018-01-07 18:53:53

标签: java json spring spring-boot

我的项目中有一个小小的初学者错误。我使用Spring Boot构建RESTful服务,而我的get方法不起作用。

我创建了一个名为Project的实体,它看起来像这样:

@Entity
@Table(name="project")
public class ProjectDto {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private long id;

    @Column(name="caption")
    private String caption;

    ..GETTERS AND SETTERS FOLLOW..

,比我创建的ProjectRepository:

@Repository
public interface ProjectRepository extends JpaRepository<ProjectDto, Long> {

    public static final String GET_TIMELINE_PROJECT_CAPTIONS_QUERY = "SELECT 
    p.id, p.caption FROM ProjectDto p ORDER BY p.creationDate DESC";

    @Query(GET_TIMELINE_PROJECT_CAPTIONS_QUERY)
    public List<ProjectDto> getTimelineProjectCaptions();

}

..和控制器

@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectRepository projectRepository;


    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/timeline", method = RequestMethod.GET)
    public List<ProjectDto> getTimelineProjectCaptions() {
        return projectRepository.getTimelineProjectCaptions();
    }

}

但这会产生[[5,"sddf"],[3,"asdf"],[2,"gb"],[1,"bg"]],显然不是JSON

3 个答案:

答案 0 :(得分:3)

是JSON。它是一个数组数组,这是您的查询实际返回的数组。

如果需要ProjectDto对象数组,则查询应为

SELECT p FROM ProjectDto p ORDER BY p.creationDate DESC

不确定为什么要使用Dto后缀命名实体。实体不是DTO。 DTO是数据传输对象,即专门为数据传输而设计的对象。

答案 1 :(得分:0)

您可以尝试将方法更改为以下内容:

@RequestMapping(value = "/timeline", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ProjectDto>> getTimelineProjectCaptions() {
    return new ResponseEntity<List<ProjectDto>>(projectRepository.getTimelineProjectCaptions(), HttpStatus.OK);
}

答案 2 :(得分:0)

您可以使用预测。

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.interfaces

如果这是你的表

@Entity
@Table(name="project")
public class Project {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name="id")
   private long id;

   @Column(name="caption")
   private String caption;

   @Temporal(TemporalType.DATE)
   @Column(name="creationDate")
   private Date creationDate;

// .. other columns ..
// ..GETTERS AND SETTERS FOLLOW..

添加基于界面的投影

public interface ProjectCaption {
  Long getId();
  String getCaption();
}

然后在查询中添加AS关键字并更改方法的返回值

@Repository
public interface ProjectRepository extends JpaRepository<Project, Long>{

    @Query("SELECT p.id AS id, p.caption AS caption FROM Project p ORDER BY p.creationDate DESC")
    public List<ProjectCaption> getTimelineProjectCaptions();

}