如何从Spring获取JSON中的相关对象?

时间:2014-03-28 10:15:50

标签: java json spring rest

我的客户端需要发送一个POST请求,其中people个对象的格式为JSON:

{
   "name":"Smith",
   "adress": {
      "city":"LA",
      "state":"CA",
      "adressId":123123
   },
   "matricule":"123"
}

我的服务器是REST服务,需要保留此对象。我的域包含一个人员bean,以及一个many to one关系的地址。

我收到请求的控制器是:

@RequestMapping(value="/people", method = RequestMethod.POST, consumes="application/json")
@ResponseBody
public void createPeople(@RequestBody People people) {
    ...
}

问题是服务器响应错误,因为它没有成功将嵌入的adress实体映射到people实体。如果我删除adress对象,它就可以工作。

是否有任何配置可以使嵌入式对象正常工作?

编辑:

@Table(name = "people")
public class People {

    @Id
    @GeneratedValue
    @Column(name = "peopleId")
    private Integer peopleId;

    @Column(name = "name")
    private String name;

    @Column(name = "matricule")
    private String matricule;

    @ManyToOne
    @JoinColumn(name="adressId")
    private Adress adress;

    // Getters and Setters

}

错误日志:

DEBUG: [mars-28 11:25:47,049] mvc.support.DefaultHandlerExceptionResolver - 
Resolving exception from handler [...createPeople()]: org.springframework.http.converter.
HttpMessageNotReadableException: Could not read JSON: Unrecognized field 
"adressId" (Class Adress), not marked as ignorable
    at [Source: org.apache.catalina.connector.CoyoteInputStream@456ce9; line: 1,
column: 106]; nested exception is org.codehaus.jackson.map.JsonMappingException: 
Unrecognized field "adressId" (Class adress), not marked as ignorable
    at [Source: org.apache.catalina.connector.CoyoteInputStream@456ce9; line: 1, 
column: 106]

我的地址类包含:

@Id
@GeneratedValue
@Column(name = "adressId")
private Integer adressId;

@Column(name = "city")
private String city;
@Column(name = "state")
private String state;

请注意,地址对象已在DB

中保留

0 个答案:

没有答案