在Spring中返回响应体内的两个对象的最佳方法是什么?

huangapple go评论140阅读模式
英文:

Best way to return 2 objects inside a response body in Spring

问题

我想将2个对象(两个不同类的实例)放在POST请求的主体中,处理这些信息,然后将更新后的对象发送回响应。最佳方法是什么?我知道可以将这些对象放入映射中或创建一个包装对象,但可能有更加优雅的方式来实现这一点。

请求主体的示例:

{
  "object1": {
    "data1": "val1",
    "data2": "val2"
  },
  "object2": {
    "dataN": "valN"
  }
}

响应主体的示例:

{
  "object1": {
    "data1": "updatedVal1",
    "data2": "val2"
  },
  "object2": {
    "dataN": "updatedValN"
  }
}
英文:

I want to send 2 objects (instances of 2 different classes) inside POST request body, process the information and the send back the updated objects in response. What is the best way of doing that ? I know I can put the objects in a map or create a wrapper object, but probably there is a more graceful way of achieving that.

Example of a request body:

{
  "object1": {
    "data1": "val1",
    "data2": "val2"
  },
  "object2": {
    "dataN": "valN"
  }
}

Example of a response body:

{
  "object1": {
    "data1": "updatedVal1",
    "data2": "val2"
  },
  "object2": {
    "dataN": "updatedValN"
  }
}

答案1

得分: 2

不,没有一种优雅的方式可以发送两个Java对象。使用一个POJO已经足够优雅了。拥有多个表示特定事物的POJO没有问题。与使用Map相比,使用POJO是更好的实践,因为它提供了类型安全性。如果您使用lombok库,可以消除所有样板代码,使您的POJO变得简洁:

@Data
public class TwoResponse {
  private OneType object1;
  private TwoType object2;
}
英文:

No, there is no graceful way of sending two java objects. Using a POJO is graceful enough. There's nothing wrong with having many POJOs that represent specific things. Using POJOs is a better practice than using a Map since it provides type safety. And if you use the lombok library you can eliminate all the boilerplate code so your POJO is nice and small:

@Data
public class TwoResponse {
  private OneType object1;
  private TwoType object2;
}

huangapple
  • 本文由 发表于 2020年8月4日 03:09:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63235528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定