Mapping a document with partly-defined schema

邮差的信 提交于 2019-11-28 02:19:23

问题


I'm writing a demo app using Spring & MongoDB as a database.

My main domain class looks like:

@Document
public class Person {

    @Id
    private String id;

    //Some other fields
    private DBObject additionalData;

}

The key is that additionalData is a subdocument with no schema specified, it is kind of user-defined JSON. But when I am parsing this json (using (DBObject) JSON.parse(value) expression), it is stored as a string in MongoDB, and I need it to be a nested document structure.

Searched for couple of hours, found no solution. Any ideas?


回答1:


I'm not really sure of the expected result of casting the result of

JSON.parse(value)

to DBObject, which is an interface, not a class. Try casting the result to an implementation of DBObject BasicDBObject (or BasicDBList), or a Map<String, Object> as mentioned in the comments (it is also an interface, but it does work).

If you're working with Spring Data Rest, you will probably not need to deserialize "manually", Spring will do it for you. Check this answer for a basic example of what to do. Having data with no schema specified may not be the best idea around (mongodb saves you from doing it at the database level, but you should do it at the application level), but I use similar tricks in production, and you can somehow make it work.



来源:https://stackoverflow.com/questions/36406195/mapping-a-document-with-partly-defined-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!