我正在使用jackson向我的控制器发送ajax json请求。这是我的实体:
@Entity
public class Template implements Serializable
{
private String templateName;
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private List<Action> actions;
//getters setters
}
我的JSON看起来像:
"{"templateName":"aaa",
"actions":["2", "3"]
}"
控制器:
@RequestMapping(value = "/testCreate", consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<ObjectError> testCreate(@Valid @RequestBody final TemplateForm templateForm,
final BindingResult bindingResult)
{
if (bindingResult.hasErrors())
{
return bindingResult.getAllErrors();
}
else
{
//some actions
return EMPTY_LIST;
}
}
如何在Action对象列表中映射JSON中的动作ID?谢谢。
答案 0 :(得分:1)
如果您使用的是Spring,可以使用 @InitBinder 。 像这样:
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(ArrayList.class, "actions",
new ActionEditor(actionService));
}
和ActionEditor将如下所示:
public class ActionEditor extends PropertyEditorSupport {
private final ActionService actionService;
public ActionEditor(ActionService actionService) {
this.ActionService = actionService;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
List<Action> facilities = new ArrayList<Action>();
String[] ids = text.split(",");
Set<Long> actionIds = new HashSet<Long>();
for (String id : ids) {
actionIds.add(Long.parseLong(id));
}
facilities.addAll(actionService.list(actionIds));
setValue(facilities);
}}