[英]Spring mvc Controller binding Nested JSON to POJO with one to many relationship
I'm trying to figure out how to bind nested JSON data received from an ajax post to a POJO that has a one to many relationship with another POJO in the spring mvc framework.我试图弄清楚如何将从 ajax 帖子接收的嵌套 JSON 数据绑定到与 spring mvc 框架中的另一个 POJO 具有一对多关系的 POJO。
for example I have 2 classes:例如我有 2 个类:
public class MagTemplate implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private BigInteger magTemplateId;
private String templateName;
//bi-directional many-to-one association to MagZone
@OneToMany(mappedBy="magTemplate", cascade = CascadeType.PERSIST)
private List<MagZone> magZones;
public MagTemplate() {
}
//getters and setters
}
public class MagZone implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private BigInteger magZoneId;
private String zoneName;
//bi-directional many-to-one association to MagTemplate
@ManyToOne
@JoinColumn(name="magTemplateId")
private MagTemplate magTemplate;
public MagZone() {
}
//getters and setters
}
And I have a JSON object that looks like this:我有一个如下所示的 JSON 对象:
{
templateName : "template 1",
magZones : [
zoneName : "zone 1"
},
{
zoneName : "zone 2"
},
zoneName : "zone 3"
}
]
}
When I tried to create a controller that looked like this:当我尝试创建一个看起来像这样的控制器时:
@RequestMapping(value = "/saveTemplate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = "application/json")
@ResponseBody
public AjaxResponse saveTemplate(HttpServletRequest request, @RequestBody MagTemplate magTemplate){
//controller code
}
and then do an ajax post like so:然后像这样做一个ajax帖子:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
contentType : "application/json",
method: "POST",
dataType: 'json',
url: url,
data: JSON.stringify(jsonData),
success: function(response){
},
error:function(jqXHR, textStatus, errorThrown){
console.error(jqXHR);
console.error('status: ' + textStatus + "\n" + "error: " + errorThrown);
}
});
I get an HTTP400 error saying that its a bad request.我收到一个 HTTP400 错误,说它是一个错误的请求。 I have the spring jackson-databind dependency and it seems to be working because I can bind a single MagZone object with another controller.我有 spring jackson-databind 依赖项,它似乎有效,因为我可以将单个 MagZone 对象与另一个控制器绑定。
How do I get the spring controller to do a deep bind of the JSON data so that I have a single MagTemplate object with a list of the 3 MagZone objects?如何让 spring 控制器对 JSON 数据进行深度绑定,以便我有一个包含 3 个 MagZone 对象列表的 MagTemplate 对象? I know that this is possible in other mvc frameworks but I cant seem to find an example of it working in spring.我知道这在其他 mvc 框架中是可能的,但我似乎找不到它在 spring 中工作的例子。
将@JsonIgnore
添加到您不在JSON
使用的字段(或方法)以从反序列化中排除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.