【问题标题】:SpringBoot : RestAPI data not populating in JSON format. (? Solution)Spring Boot:Rest API 数据未以 JSON 格式填充。 (? 解决方案)
【发布时间】:2020-07-22 12:29:32
【问题描述】:

问题: 获取以下格式的数据,但我想要 JSON 格式,以便我可以绑定它。

[[1,"User"],[2,"Visitor"]]

存储库:

@Repository
public interface CategoryRepository extends JpaRepository<ccCategory,Integer>
{

    public static final String FIND_CATEGORYNAME = "SELECT DISTINCT catID,categoryName from XXCategory";

    @Query(value = FIND_CATEGORYNAME, nativeQuery = true)
    List<Object> getCategoryName();

}

控制器:

@RestController
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
public class HomeResource {

    private final Logger log = LoggerFactory.getLogger(HomeResource.class);

    @Autowired
    CategoryRepository categoryRepository;



@GetMapping("/getAllCategory")
        public List<Object> getAllCategory() {
        System.out.println("***** Call : API getAllCategory() ******");
        List<Object> cCategory = categoryRepository.getCategoryName();
        return cCategory;
    }

【问题讨论】:

  • 阅读文档并了解可用的工具。您可以使用 Spring Data Projection 返回字段的子集。没有返回所需对象数组的 SQL 查询。任务完成。 baeldung.com/spring-data-jpa-projections

标签: spring-boot spring-mvc spring-data-jpa


【解决方案1】:

这仍然是有效的 JSON!

如果你想把它包装在一个对象中,你需要创建一个响应模型如下:

public class Categories implements Serializable {

    public List<Object> category;
}

我还建议您对此进行扩展并创建一个Category 实体,而不是使用Object。这也将为嵌套数组中的字段创建映射。从您的存储库中,我可以看到您已经拥有某种 Category 实体,所以也许您可以重用它。

然后您的控制器可以返回 Categories 或更好的 ResponseEntity&lt;Categories&gt; 以返回正确的响应。在这种情况下,您可以返回包裹在 org.springframework.http.ResponseEntity.ok 方法中的 cCategory

您也可以跳过Categories 对象并使用Category 实体。这取决于你追求什么。如果您提供预期的输出,将会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多