2012-10-03 27 views
4

我有一個Update對象的實例,我想將它轉換爲它的String JSON表示,以便稍後使用它。將Spring Mongo更新轉換爲JSON字符串

我創造了這樣的更新對象:

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

我最初的嘗試是:

update.getUpdateObject().toString(); 

這種方式工作了大多數情況下,但因爲它不能序列化的SomeClass的情況下偶爾會失敗。這是堆棧跟蹤:

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) 

我有可用的MongoTemplateMongoConverter實例,但我不確定如何使用這些類來完成這一任務。

的問題是:

什麼是獲得一個更新對象的JSON表示的正確方法是什麼?

我正在使用spring-data-mongodb版本1.1.0.M1。

+0

只是爲了驗證,是''SomeClass'序列化'? – sbzoom

回答

1

您可以通過使用做到這一點,

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()); 
0

我遇見了同樣的問題,解決了轉SomeClassDBObject

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

update.set("field", dbObject);