Java Spring建模:字段作为接口

Java Spring建模:字段作为接口,java,mongodb,spring-data-mongodb,Java,Mongodb,Spring Data Mongodb,有没有办法在文档的模型中放置一个字段作为接口?例如: public class Foo { private String id; private Bar bar; } 其中,Bar是一个具有多个实现的接口。在这个条中有一个方法签名String getType(),它告诉我可以使用哪个实现来映射数据库中的数据 我尝试了不同的解决方案(@ReadingConverter/@WiritingConverter,@JsonSerialize/@JsonSerialize),但没有结果。

有没有办法在文档的模型中放置一个字段作为接口?例如:

public class Foo {
    private String id;
    private Bar bar;
}
其中,
Bar
是一个具有多个实现的接口。在这个条中有一个方法签名
String getType()
,它告诉我可以使用哪个实现来映射数据库中的数据

我尝试了不同的解决方案(
@ReadingConverter
/
@WiritingConverter
@JsonSerialize
/
@JsonSerialize
),但没有结果。每次我得到

实例化[Bar]失败:指定的类是接口


有什么帮助吗?谢谢大家!

看起来您需要多态序列化/反序列化。你应该看看杰克逊的文档:

简而言之,您将需要执行类似的操作,其中使用
@JsonTypeIdResolver
注释定义自定义类型解析器:

@JsonTypeInfo(use = @JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.PROPERTY, 
    property = "@type"
)
@JsonTypeIdResolver(BarTypeIdResolver.class)
public interface Bar {
    ...
}

public class BarTypeIdResolver extends TypeIdResolverBase {
    // boilerplate skipped, see the documentation
     
    @Override
    public String idFromValueAndType(Object obj, Class<?> subType) {
        String typeId = null;
        if (obj instanceof Bar) {
            Bar bar = (Bar) obj;
            typeId = bar.getType();
        }
        return typeId;
    }
 
    @Override
    public JavaType typeFromId(DatabindContext context, String id) {
        Class<?> subType = null;
        switch (id) {
        case "barImpl1":
            subType = BarImpl1.class;
            break;
            ...
        }
        return context.constructSpecializedType(superType, subType);
    }
}
@JsonTypeInfo(use=@JsonTypeInfo(
use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.PROPERTY,
property=“@type”
)
@JsonTypeIdResolver(BarTypeIdResolver.class)
公共接口栏{
...
}
公共类BarTypeIdResolver扩展了TypeIdResolverBase{
//跳过样板文件,请参阅文档
 
@凌驾
公共字符串idFromValueAndType(对象对象对象,类子类型){
字符串typeId=null;
if(obj杆实例){
Bar=(Bar)obj;
typeId=bar.getType();
}
返回typeId;
}
 
@凌驾
公共JavaType类型FromId(DatabindContext上下文,字符串id){
类子类型=null;
开关(id){
案例“1”:
subType=BarImpl1.class;
打破
...
}
返回context.constructedSpecializedType(超类型,子类型);
}
}

好吧,假设我想映射多态geoJson数据,所以在我的例子中,接口是
org.springframework.data.mongodb.core.geo.geoJson
所以我不能修改它。你可以为你不能修改的类向Jackson添加装饰类:
mapper.addMixIn(geoJson.class,GeoJsonMixin.class)
在这里创建
GeoJsonMixin
类以包含所需的注释。这是唯一的方法吗?