Convert Spring Mongo Update to JSON String

I have an instance of an Update object, and I would like to convert it to its String JSON representation so that I can use it later.

I created the update object as follows:

 Update update = new Update(); update.set("field", new SomeClass()); update.unset("otherField"); // etc 

My initial attempt:

 update.getUpdateObject().toString(); 

This approach worked in most cases, but sometimes it was interrupted because it could not serialize an instance of SomeClass . This was a 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 an instance of MongoTemplate and MongoConverter , but I'm not sure how to use these classes to complete this task.

The question arises:

What is the correct way to get the JSON representation of an Update object?

I am using spring-data-mongodb version 1.1.0.M1.

+4
source share
2 answers

You can do this 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()); 
+1
source

I ran into the same problem and solved by turning SomeClass into a DBObject :

 DBObject dbObject = new BasicDBObject(); dbObject.put("fieldA", "a"); // set all fields of SomeClass ... update.set("field", dbObject); 
0
source

Source: https://habr.com/ru/post/1437494/


All Articles