Reputation: 11779
I have an instance of an Update
object and I would like to convert it to its String JSON representation so I can use it later.
I created the update object like this:
Update update = new Update();
update.set("field", new SomeClass());
update.unset("otherField");
// etc
My initial attempt was:
update.getUpdateObject().toString();
This approach worked for most cases but it failed occasionally because it could not serialize an instance of SomeClass
. This was the stacktrace:
java.lang.RuntimeException: json can't serialize type : class com.example.SomeClass
at com.mongodb.util.JSON.serialize(JSON.java:261)
at com.mongodb.util.JSON.serialize(JSON.java:115)
at com.mongodb.util.JSON.serialize(JSON.java:161)
at com.mongodb.util.JSON.serialize(JSON.java:141)
at com.mongodb.util.JSON.serialize(JSON.java:58)
at com.mongodb.BasicDBObject.toString(BasicDBObject.java:84)
I have available an instance of MongoTemplate
and MongoConverter
but I am unsure about how to use these classes to do this task.
The question is:
What's the correct way to get the JSON representation of an Update object?
I'm using spring-data-mongodb version 1.1.0.M1.
Upvotes: 4
Views: 3582
Reputation: 103
I've met the same problem, and solved by turning SomeClass
into DBObject
:
DBObject dbObject = new BasicDBObject();
dbObject.put("fieldA", "a"); // set all fields of SomeClass
...
update.set("field", dbObject);
Upvotes: 0
Reputation: 3855
You can do this by using,
Update update = new Update();
JSONObject jsonObject = new JSONObject(new SomeClass());
update.set("field",JSON.parse(jsonObject.toString()));
update.unset("otherField");
System.out.println(update.getUpdateObject().toString());
Upvotes: 1