Skip to content

Mapping Objects from and to Strings

Stephan Bösebeck edited this page Aug 23, 2013 · 1 revision

Why strings?

yes, the whole Mongo communication is based on BSON-Objects which is totally fine for performance. BSON Objects can very easily be cast to a "normal" Json string using the .toString() method. But unfortunately i did not find a way back... Sometimes it might be useful to be able to parse strings stored in files or even in Mongo -> endless possibilities ;-)

How does it work

I added one new dependency to a "Simple JSon Parser" which does excactly, what the name states: simply parsing Json. In our case into BSon representation. This can than easily be put into the "normal" mapping algorithm to create the corresponding Java-Class.

    String json=morphium.getMapper().marshall(myEntity).toString();
    MyEntity myEntity=morphium.getMapper().unmarshall(MyEntity.class,json)


When de-serializing your json string, you need to know, which class to use to de-serialize the data into. If you have several different objects stored in your json text, you probably should set @Embedded(polymorph=true) as annotation to your entity. (Polymorph objects cause morphium to store the classname) One other thing: if you don't want to use ids in your object, use the @Embedded annotation...

ATTENTION: right now, this string parsing can parse one Json object at a time, so you cannot have several objects stored in one string. If there is need for changing that, contact me...

You can’t perform that action at this time.