[英]Save json date field with date format on MongoDB
I am using Mongo DB and on saveData method I'm trying to save the data object on Mongo DB. 我正在使用Mongo DB,并在saveData方法上尝试将数据对象保存在Mongo DB上。 First I am converting the data object in JSON format and after I save the object on Mongo DB.
首先,我将数据对象转换为JSON格式,然后将对象保存在Mongo DB上。 But there's a problem.
但是有一个问题。 My Class Object has a atribute initialDate with Date Type, but when this code saves the object on Mongo the initialDate atribute is saved as a string, but I need that it be saved in date format.
我的班级对象具有日期类型的属性initialDate,但是当此代码将对象保存在Mongo上时,initialDate属性被保存为字符串,但是我需要将其保存为日期格式。 Someone can help me?
有人可以帮我吗?
public void saveData(ClassObject data) {
JSONObject jsonObject = new JSONObject(data);
String dataJson = jsonObject.toString();
DBObject dbObject = (DBObject) JSON.parse(dataJson);
DBCollection table = mongoDB.getCollection(data
.getModel().getProjectName());
table.insert(dbObject);
}
Here the ClassObject 这里的ClassObject
Class ClassObject {
private int value;
private ParentModel model;
private Date initialDate;
...
//here get and setters
}
Your date
is getting converted into string while doing toString
on jsonObject
. 在
jsonObject
上执行toString
,您的date
将转换为字符串。 You need to convert it back to date
type after you do JSON.parse
- 执行
JSON.parse
之后,您需要将其转换回date
类型-
DBObject dbObject = (DBObject) JSON.parse(dataJson);
// TODO: Convert dbObject's initialDate property back to date type here
DBCollection table = mongoDB.getCollection(data
.getModel().getProjectName());
Converting the object to JSON will convert the date to a string as JSON does not have a date type. 将对象转换为JSON会将日期转换为字符串,因为JSON没有日期类型。
You can manually set the initialDate
in the dbObject
like so 您可以像这样手动在
dbObject
设置initialDate
dbObject.put("initialDate", data.getInitialDate());
and this should save the date as a date. 并将日期保存为日期。
A better solution would be to use a library to map between the java classes and json, as described here https://stackoverflow.com/a/7684293/965322 更好的解决方案是使用库在java类和json之间进行映射,如此处所述https://stackoverflow.com/a/7684293/965322
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.