小编404*_*505的帖子

返回 JSON 作为 Spring Boot 响应

我正在尝试以 json 形式获取休息响应,而不是以字符串形式获取。

控制器

@RestController
@RequestMapping("/api/")
public class someController{

  @Autowired
  private SomeService someService;

  @GetMapping("/getsome")
  public Iterable<SomeModel> getData(){
    return someService.getData();
  }
}
Run Code Online (Sandbox Code Playgroud)

服务

@Autowired
private SomeRepo someRepo;

public Iterable<someModel> getData(){
  return someRepo.findAll();
}
Run Code Online (Sandbox Code Playgroud)

存储库

public interface SomeRepo extends CrudRepository<SomeModel,Integer>{

}
Run Code Online (Sandbox Code Playgroud)

楷模

@Entity
@Table(name="some_table")
public class SomeModel{

  @Id
  @Column(name="p_col", nullable=false)
  private Integer id;
  @Column(name="s_col")
  private String name
  @Column(name="t_col")
  private String json;   // this column contains json data

  //constructors, getters and setters
}
Run Code Online (Sandbox Code Playgroud)

当我运行localhost:8080/api/getsome时我得到:

[
 {
    "p_col":1,
    "s_col":"someName",
    "t_col":" 
{\r\n\t"school_name\":\"someSchool\",\t\r\n\t"grade\":"A\",\r\n\t\"class\": 
 [{\"course\":"abc",\t"course_name\":\"def" …
Run Code Online (Sandbox Code Playgroud)

spring spring-data spring-data-jpa spring-data-rest spring-boot

6
推荐指数
1
解决办法
1万
查看次数