使用外键从JSON反序列化 [英] Deserializing from JSON using foreign key

查看:75
本文介绍了使用外键从JSON反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一对多的关系: A *<-> 1 B ,我想从具有 B 的JSON反序列化 A strong>的主键(具有该主键的 B 存在于db中):

I have a many to one relationship: A *<-->1 B and I want to deserialize A from a JSON having B's primary key (B exists in db with that primary key):

{
    "b": 1
}

我尝试了以下操作:

@Entity
@Table(name = "table_a")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class A implements Serializable {

    @JsonIgnore
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "b", unique = true, nullable = false)
    private B b;
}

@Entity
@Table(name = "table_b")
public class B implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @OneToMany(mappedBy = "b")
    private List<A> a = new ArrayList<>();
}

但是对象 A 是使用b = null创建的.如何使用从数据库正确实例化的 b 属性反序列化 A ?

but object A is created with b = null. How can I deserialize A with b property correctly instantiated from db?

注意:我正在使用杰克逊2.6.1版.

Note: I am using Jackson version 2.6.1.

推荐答案

您有几种选择,这是类似的问题 :

You have several options and here is similar question :

    类中的
  1. @JsonCreator工厂(更多信息)

自定义反序列化器

@JsonIdentityInfo自定义ObjectIdResolver

private class MyObjectIdResolver implements ObjectIdResolver {
    private Map<ObjectIdGenerator.IdKey,Object> _items  = new HashMap<>();

    @Override
    public void bindItem(ObjectIdGenerator.IdKey id, Object pojo) {
        if (!_items.containsKey(id)) _items.put(id, pojo); 
    }

    @Override
    public Object resolveId(ObjectIdGenerator.IdKey id) {
        Object object = _items.get(id);
        return object == null ? getById(id) : object;
    }

    protected Object getById(ObjectIdGenerator.IdKey id){
        Object object = null;
        try {
            //can resolve object from db here
            //objectRepository.getById((Integer)idKey.key, idKey.scope)
            object = id.scope.getConstructor().newInstance();
            id.scope.getMethod("setId", int.class).invoke(object, id.key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @Override
    public ObjectIdResolver newForDeserialization(Object context) {
        return new MyObjectIdResolver();
    }

    @Override
    public boolean canUseFor(ObjectIdResolver resolverType) {
        return resolverType.getClass() == getClass();
    }
}

并像这样使用它:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
        resolver = MyObjectIdResolver.class, 
        property = "id", scope = B.class)
public class B  {
   // ...
}

这是与您的案例有关的要点演示更广泛的

Here is your case related gist demo more broad github project with some serialization thoughts

这篇关于使用外键从JSON反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆