【问题标题】:Deserialize json ids to list of objects将 json id 反序列化为对象列表
【发布时间】:2017-11-09 16:05:37
【问题描述】:

我正在使用 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;
        }
    }

如何将 JSON 中的动作 ID 映射到动作对象列表上?谢谢。

【问题讨论】:

  • 你能发布你的控制器代码吗?
  • 准备好了)))))))))))))))

标签: java json hibernate jackson


【解决方案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);
}}

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 2012-03-07
    • 2023-03-13
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多