new Gson().toJson(new ObjectId())
When I do the above, the output I get is
"_id" : { "_time" : 1374347520 , "_machine" : -1025067326 , "_inc" : 585905201 , "_new" : false}
But Actually I want it to be as
"_id":{"$oid":51eae100c2e6b6c222ec3431}
which is the usual mongodb ID format. What is the preferable method in Java for this?
Update:
My value object
import com.google.gson.annotations.SerializedName;
import org.bson.types.ObjectId;
public class TaskObject {
@SerializedName("_id")
private ObjectId _id;
@SerializedName("revNo")
private int revNo;
}
I am trying to store this to mongodb with a custom _id
TaskObject taskObject = new TaskObject();
taskObject.set

在Java中,将BSON类型的ObjectId转换为JSON时,通常会得到包含_time、_machine、_inc和_new的格式。为了得到MongoDB标准的_id格式(即{"$oid": "xxxx"}),你需要创建一个实现TypeAdapter的ObjectIdTypeAdapter,并将其注册到GsonBuilder。通过这个适配器,可以确保 ObjectId 在序列化和反序列化时保持正确格式。
最低0.47元/天 解锁文章
525

被折叠的 条评论
为什么被折叠?



