Spring Boot - 返回JSON数据的最佳方式

时间:2022-09-11 14:58:49

Actually I am building a REST API and there are many differents ways to return the JSON data. But I want to know a good one that can be scalable in time and taking care of many to many relationships, and deep relations (Article -> has Category -> has Department -> etc..)

实际上我正在构建一个REST API,并且有许多不同的方法可以返回JSON数据。但我想知道一个好的,可以及时扩展并处理多对多关系,以及深层关系(文章 - >有类别 - >有部门 - >等...)

Some few options:

几个选项:

1) DTO pattern and building it manually taking care of the "fields" parameter of the request.

1)DTO模式并手动构建它,处理请求的“fields”参数。

2) The @JsonView(View.Example.class) at Entity class.

2)Entity类中的@JsonView(View.Example.class)。

3) The default JSON serialization on Spring Boot (Jackson).

3)Spring Boot(Jackson)上的默认JSON序列化。

I think the more scalable option is the 1st, where I can handle the many to many relations and other stuff... What do you think?

我认为更具伸缩性的选择是第一,我可以处理多对多的关系和其他东西...你怎么看?

1 个解决方案

#1


0  

I think the best way is to mix both option 1 and 3.

我认为最好的方法是混合选项1和3。

You should have a converter to convert an Entity into a Response DTO. There you can map all your deep relations. Just make sure that you have all your deep relations loaded before the converter kicks in to prevent multiple database reads.

您应该有一个转换器将实体转换为响应DTO。在那里你可以映射你所有的深层关系。只需确保在转换器启动之前加载了所有深层关系,以防止多个数据库读取。

When you're finished, Jackson will do the job.

当你完成后,杰克逊将完成这项工作。

#1


0  

I think the best way is to mix both option 1 and 3.

我认为最好的方法是混合选项1和3。

You should have a converter to convert an Entity into a Response DTO. There you can map all your deep relations. Just make sure that you have all your deep relations loaded before the converter kicks in to prevent multiple database reads.

您应该有一个转换器将实体转换为响应DTO。在那里你可以映射你所有的深层关系。只需确保在转换器启动之前加载了所有深层关系,以防止多个数据库读取。

When you're finished, Jackson will do the job.

当你完成后,杰克逊将完成这项工作。