在 JAVA 的 restful Web 服务中处理复杂对象的最佳实践是什么
what is the best practice for handle complex object in a restful web services in JAVA
我有一个复杂的 class,里面有很多对象,当我执行 GET 时,我想查看包含所有内部对象数据的完整对象,但是当我 POST 时,我只想要为内部对象传递 ID。
示例:
class ComplexObject {
private InnerObject1 innerObject1;
private InnerObject2 innerObject2;
//setters and getters
}
当我执行 GET 时,我想检索完整的 JSON,这是简单的部分,但是当我保存 ComplexObject 时,我只想传递 innerObject1 和 innerObject2 的 ID,而不是整个对象。
我怎样才能做到这一点?
当您 post 对象时,您可以解析 JSON 您在控制器中通过 ID 发送和检索所需的对象,然后在那里重建对象并发送要创建的完整对象.
例如,假设您有一个 ObjectController,并且在 post 路线上您将构建一个复杂的 JSON.
//Post request to this method
public void addObject(@RequestBody Object obj) {
Object newObj = new Object(obj);
//Get the full objects by id
InnerObject innerObj = innerObjectService.findById(obj.innerObjectId);
//Build the full new object
newObj.setInnerObj(innerObj);
//Create the object
...
}
您不应使用 Hibernate 实体在 REST 调用中发送和接收数据。为此使用单独的对象 - 数据传输对象 (DTO) - What is Data Transfer Object?。在你的情况下,它可能是 ComplexObjectWithIds
只包含 ids:
@POST
@Path("/complex-object")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postComplexObject(ComplexObjectWithIds complexObjectWithIds)
和ComplextObjectFull
具有完整数据:
@GET
@Path("/complex-object")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ComplextObjectFull getComplexObject()
我有一个复杂的 class,里面有很多对象,当我执行 GET 时,我想查看包含所有内部对象数据的完整对象,但是当我 POST 时,我只想要为内部对象传递 ID。
示例:
class ComplexObject {
private InnerObject1 innerObject1;
private InnerObject2 innerObject2;
//setters and getters
}
当我执行 GET 时,我想检索完整的 JSON,这是简单的部分,但是当我保存 ComplexObject 时,我只想传递 innerObject1 和 innerObject2 的 ID,而不是整个对象。
我怎样才能做到这一点?
当您 post 对象时,您可以解析 JSON 您在控制器中通过 ID 发送和检索所需的对象,然后在那里重建对象并发送要创建的完整对象.
例如,假设您有一个 ObjectController,并且在 post 路线上您将构建一个复杂的 JSON.
//Post request to this method
public void addObject(@RequestBody Object obj) {
Object newObj = new Object(obj);
//Get the full objects by id
InnerObject innerObj = innerObjectService.findById(obj.innerObjectId);
//Build the full new object
newObj.setInnerObj(innerObj);
//Create the object
...
}
您不应使用 Hibernate 实体在 REST 调用中发送和接收数据。为此使用单独的对象 - 数据传输对象 (DTO) - What is Data Transfer Object?。在你的情况下,它可能是 ComplexObjectWithIds
只包含 ids:
@POST
@Path("/complex-object")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postComplexObject(ComplexObjectWithIds complexObjectWithIds)
和ComplextObjectFull
具有完整数据:
@GET
@Path("/complex-object")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ComplextObjectFull getComplexObject()