user748316
user748316

Reputation: 348

How to persist a sub-document of arbitrary data to MongoDB using Spring Data?

I am trying to insert a document(json string) in a mongo db. One of the key "profile" of this has a value which is a json string. So, basically its a nested json structure. I know its possible to insert a nested json by abusing collection-refs / one-may relationships in the document class.

The issue I am facing here is that the json structure of the nested part is not fixed and hence cannot be abstracted to a java class as it is a custom data json fetched from social networking APIs. Defining "profile" as Java string inserts profile data with slashes thus escaping the double-quotes, curly brackets, etc. in json data .

Is there any other way without casting it to another object.

Upvotes: 5

Views: 1984

Answers (2)

Jonathan Crosmer
Jonathan Crosmer

Reputation: 786

The answer of using a Map was a little unclear to me... how do you convert an arbitrary JSON String to a Map in a way that Spring Data will persist it as-is?

I found that using a property of type "com.mongodb.DBObject" works. Then set your property using JSON.parse:

profile = (DBObject) JSON.parse(arbitraryJSONString)

Upvotes: 0

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83081

The way to go is probably to make profile a Map<String, Object> in the containing class. This way, you can store arbitrary data within it.

 class MyDocument {

   Map<String, Object> profile;
 }

Upvotes: 3

Related Questions