java - 将 json id 反序列化为对象列表

标签 java json hibernate jackson

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

相关文章:

java - Hibernate - 回滚 : org. hibernate.MappingException:未知实体

java - 在多线程中 hibernate @GeneratedValue序列

java - 尝试分块上传

java - 如何使用project/Build.scala生成java playproject?

php - JSON 响应 header

java - Java 的 JSON 美化器库

arrays - 如何跨jq中的多个对象收集数组值字段的唯一元素?

java - 从另一个方法调用的@Transactional 方法没有获得事务

java - Spring @profile 如何与继承一起工作?

javascript - 如何使用泛型在 TypeScript 中模拟 Java getClass()?