lacripta
lacripta

Reputation: 112

Morphia ignores TypeConverter

i'm using morphia v1.3.2 with JDK7, i have documents represented by Objects and sub classes. after struggling for a while with morphia to make use of it's internal mapper i found a way to change the way a class is de/serialized according to their docs and other posts, i found that all that is required is to have a class like this:

public class MyClassTypeConverter extends TypeConverter {

    public ActionTypeConverter() {
        super(MyClass.class);
    }

    @Override
     public Object decode(final Class targetClass, final Object fromDBObject, final MappedField optionalExtraInfo) {
          //do something to parse my class
          return new MyClass((DBObject) fromDBObject);
     }

     @Override
     public Object encode(final Object value, final MappedField optionalExtraInfo) {
        //do something to represent this  as JSON
        return value.toString();
     }
}

after registering this typeConverter like this

morphia.getMapper().getConverters().addConverter(new MyClassTypeConverter());

it should now allow to de/serialize the document using the methods supplied. but for some reason every converter being registered is completely ignored, is there a reason to this behavior?

NOTE: i found the solution to this problem. only leaving this question here for reference.

Upvotes: 1

Views: 531

Answers (1)

lacripta
lacripta

Reputation: 112

after scouring the source code of morphia converters i found that every registered converter implements SimpleValueConverter which by the way has a really misleading documentation (Marker interface that the TypeConverter returns simple values (int/long, string, etc...))

public class MyClassTypeConverter extends TypeConverter implements SimpleValueConverter {

    public ActionTypeConverter() {
        super(MyClass.class);
    }

    @Override
     public Object decode(final Class targetClass, final Object fromDBObject, final MappedField optionalExtraInfo) {
          //do something to parse my class
          return new MyClass((DBObject) fromDBObject);
     }

     @Override
     public Object encode(final Object value, final MappedField optionalExtraInfo) {
        //do something to represent this  as JSON
        return value.toString();
     }
}

when i implemented it, i had my doubts but for some reason my converter wasn't ignored and the document was parsed as it should, everything worked like magic, it was like something clicked and finally i was frustrated no more. i hope someone finds this useful

Upvotes: 4

Related Questions