【问题标题】:How to send inherited Object with JSON in Spring Controller?如何在 Spring Controller 中使用 JSON 发送继承的对象?
【发布时间】:2015-09-11 16:57:18
【问题描述】:

我使用 Hibernate,除了这种情况,一切都很好。如果我有类和继承类,当我在 Spring Controller 中使用 JSON 发送对象时,总是会收到错误 400 BadRequest。

如果我发送一个不是子类的对象,则所有字段都可以很好地循环并且所有内容都可以很好地存储。 这是示例:

@Entity
@javax.persistence.Table(name="person")
@Inheritance(strategy=InheritanceType.JOINED)
public class Person{
@Id
@GeneratedValue
@Column(name="id_person")
protected int id_person;
.....

@Entity
@javax.persistence.Table(name="client")
@PrimaryKeyJoinColumn(name="id_person")
public class Client extends Person{

@Column(name="address")
protected String address;
....

@Entity
@javax.persistence.Table(name="individual")
@PrimaryKeyJoinColumn(name="id_person")
public class Individual extends Client {

@Column(name="personal_number")  
protected String personalNumber;
.....

我在Controller中的方法:

@RequestMapping(value="/individualPerson", method=RequestMethod.POST)
public ResponseEntity<List<Individual>> posttest(HttpServletRequest request,   HttpServletResponse response, @RequestBody Individual indiv)

发送继承对象时是否需要一些额外的注释或设置?

此外,Hibernate 会自动创建所有具有在这些类中注释的主键的表。

【问题讨论】:

  • 使用 Http 状态,您无法知道发生了什么问题。尝试使用REST-CLINET-UI 之类的方法来获取您的堆栈跟踪。
  • 我试试,Rest-ClientUI你有什么推荐

标签: java json spring hibernate inheritance


【解决方案1】:

如果使用 JSON 格式,Jackson library 默认不需要任何特殊注解。 Spring 开箱即用地支持它,因此通常您不需要指定任何其他内容:

@RequestMapping(value="/individualPerson", method=RequestMethod.POST, produces="application/json")

另一种选择是依赖HTTP内容协商,Spring支持,在produces属性中不指定任何格式

【讨论】:

    【解决方案2】:

    如果您的路径中有 Jackson 库,您将进行两项更改:

    1. 在方法或返回类型上标记@ResponseBody 注释。
    2. produces 属性集添加到@RequestMapping 上的org.springframework.http.MediaType.APPLICATION_JSON

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-16
      • 2023-03-27
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      相关资源
      最近更新 更多