枚举列表的Morphia界面不起作用(解组)

时间:2014-09-19 07:16:34

标签: morphia

我有以下界面

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "className")
public interface InfoChartInformation {
    public String name();
}

以下实现(枚举):

public class InfoChartSummary {    
    public static enum Immobilien implements InfoChartInformation {
        CITY, CONSTRUCTION_DATE;
    }
    public static enum Cars implements InfoChartInformation {
        POWER, MILEAGE;
    }
}

然后我在以下实体中使用所有It:

@Entity(noClassnameStored = true)
@Converters(InfoChartInformationMorphiaConverter.class)
public class TestEntity{
    @Id
    public ObjectId id;
    @Embedded
    public List<InfoChartInformation> order;
}
杰克逊为了检测解组时的类型,会在列表中的每个枚举中添加className。

我认为morphia会做同样的事情,但枚举列表中没有字段className,并且无法正确解组java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb .DBObject

我想正确的行为应该是保存所有枚举路由(包+名称),而不仅仅是枚举名称。至少以这种方式可以执行解组。有一种方法,morphia默认支持,或者我需要创建自己的转换器(similar to this)?

2 个答案:

答案 0 :(得分:1)

我尝试创建自定义转换器:

public class InfoChartInformationMorphiaConverter extends TypeConverter{
    public InfoChartInformationMorphiaConverter() {
        super(InfoChartInformation.class);
    }
    @Override
    public Object decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) {
        if (fromDBObject == null) {
            return null;
        }
        String clazz = fromDBObject.toString().substring(0, fromDBObject.toString().lastIndexOf("."));
        String value = fromDBObject.toString().substring(fromDBObject.toString().lastIndexOf(".") + 1);
        try {
            return Enum.valueOf((Class)Class.forName(clazz), value);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }
    @Override
    public Object encode(final Object value, final MappedField optionalExtraInfo) {
        return value.getClass().getName() + "." + ((InfoChartInformation) value).name();
    }
}

然后,我将转换器信息添加到morphia morphia.getMapper().getConverters().addConverter(new InfoChartInformationMorphiaConverter());

但是,在序列化(或编组)对象以将其保存到数据库中时,将忽略自定义转换器并使用默认的Morphia转换器(仅枚举名称)保存枚举。 / p>

如果我在TestEntity类只使用属性InfoChartInformation;而不是List<>InfoChartInformation>,我的客户转换器就可以使用。但是我需要支持List

答案 1 :(得分:0)

使用:

public class InfoChartInformationMorphiaConverter extends TypeConverter implements SimpleValueConverter

这是使Converter正常工作所必需的标记器界面。

相关问题