长话短说:是否可以使用Morphia为第三方库类编写类型转换器?
长篇故事:我是Morphia的新手。我有一个实体类,其中包含一个键入 javax.activation.MimeType 的字段。当我尝试保存我的类的实例时,Morphia抱怨它“无法序列化类javax.activation.MimeType”。我尝试编写TypeConverter并将其添加到转换器列表中但它不起作用。 以下是代码:
@Entity
@Converters(MimeTypeConverter.class)
public class Entity {
@Id ObjectId id;
String name;
javax.activation.MimeType mimeType;
}
public class MimeTypeConverter extends TypeConverter {
@Override
public Object decode(Class targetClass,
Object fromDBObject,
MappedField optionalExtraInfo) {
MimeType mimetype;
BasicDBObject dbObject = (BasicDBObject) fromDBObject;
String mimeString = dbObject.getString("mimeType");
try{
mimetype = new MimeType(mimeString);
} catch(MimeTypeParseException ex){
mimetype = new MimeType();
}
return mimetype;
}
@Override
public Object encode(Object value, MappedField optionalExtraInfo) {
MimeType mimetype = (MimeType) value;
return mimetype.getBaseType();
}
@Override
public Class[] getSupportTypes() {
return new Class[]{MimeType.class};
}
}
Morphia morphia = new Morphia().map(Entity.class);
morphia.getMapper().getConverters().addConverter(new MimeTypeConverter());
Datastore ds = morphia.createDatastore(new MongoClient(), "test"); //UnknownHostException
Entity entity = new Entity();
entity.name = "test name";
entity.mimeType = new MimeType("text/plain"); //MimeTypeParseException
ds.save(entity); // FAILS WITH ERROR HERE
我希望MimeType类以“foo / bar”样式序列化,并从中反序列化。这可能吗?
答案 0 :(得分:5)
这实际上适用于我使用0.107代码。我正在使用一个稍微修改过的转换器,这可能有助于我的成功。我正在使用的转换器以及测试。
@Entity
@Converters(MimeTypeConverter.class)
public static class MimeTyped {
@Id
private ObjectId id;
private String name;
private javax.activation.MimeType mimeType;
}
public class MimeTypeConverter extends TypeConverter {
public MimeTypeConverter() {
super(MimeType.class);
}
@Override
public Object decode(final Class targetClass, final Object fromDBObject, final MappedField optionalExtraInfo) {
try {
return new MimeType(((BasicDBObject) fromDBObject).getString("mimeType"));
} catch (MimeTypeParseException ex) {
return new MimeType();
}
}
@Override
public Object encode(final Object value, final MappedField optionalExtraInfo) {
return ((MimeType) value).getBaseType();
}
}
@Test
public void mimeType() throws UnknownHostException, MimeTypeParseException {
getMorphia().getMapper().getConverters().addConverter(new MimeTypeConverter());
MimeTyped entity = new MimeTyped();
entity.name = "test name";
entity.mimeType = new MimeType("text/plain"); //MimeTypeParseException
final DBObject dbObject = getMorphia().toDBObject(entity);
assertEquals("text/plain", dbObject.get("mimeType"));
getDs().save(entity);
}