2014-09-04 31 views
0

我堅持一個JSON對象的MongoDB這裏是相關的代碼片段:持久化JSON來的MongoDB如何指定日期屬性

Viewed: [ 
-{ 
ViewedID: "8992ade400a" 
Dockey: "3323aba3233" 
PID: "32399a" 
actionsTaken: "email|direct message|report seeker" 
viewDate: "01-APR-2014" 
MessageSent: "true" 
-Message: [ 
-{ 
MessageID: "123aca323" 
Delivered: "True" 
Opened: "True" 
ClickThroughRate: "NotBad" 
MessageDate: "02-APR-2014" 
-Response: [ 
-{ 
ResponseId: "a323a9da" 
ResponseDate: "23-APR-2014" 
} 
] 
} 

這裏是我如何我堅持對象上設置JSON:

trackingData.setEventdata((DBObject)JSON.parse(tracker.getEventData().toString())); 

其中tracker.getEventData()返回ObjectNode當我堅持DBObject到mongo我看到日期如"viewDate" : "01-APR-2014""ResponseDate" : "23-APR-2014"作爲字符串。

我需要將這些屬性轉換爲類型日期,以便我可以查詢這些日期。無論如何要指定將這些JSON解析爲DBObject之前或之後,將它們作爲日期對象進行處理?

乾杯,

威爾

回答

0

com.mongodb.util.JSON.parse方法支持Extended JSON format,所以如果JSON實際上格式化這樣那麼這將被自動轉換爲日期。

但是既然不是,那麼你需要實現一個自定義分析器來處理你的JSON中的「date」元素,否則在發送給MongoDB之前只是操縱BSON。

最簡單的方法就是操縱,喜歡的東西在這個例子中,如下所示:

try { 
     DBObject content = (DBObject)com.mongodb.util.JSON.parse("{ \"date\": \"01-APR-2014\" }"); 
     System.out.println(content); 

     SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); 
     sdf.setTimeZone(TimeZone.getTimeZone("GMT")); 
     content.put("date",sdf.parse((String) content.get("date"))); 

     System.out.println(content); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 

所以處理後的.parse()你基本上可以做到這一點的日期轉換爲源每個相關日期字段。另請注意,數據將以日期「UTC/GMT」存儲,因此請確保您從源獲取的時區正確表示。