我正在使用 jackson 向我的 Controller 发送 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"]
}"
Controller :
@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;
}
}
如何将 JSON 中的操作 ID 映射到操作对象列表上?谢谢。
最佳答案
如果您使用 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);
}}
关于java - 将 json id 反序列化为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47206452/