java bson json 转换,将BSON类型ObjectId转换为JSON(存储在Mongodb中)-Java

在Java中,将BSON类型的ObjectId转换为JSON时,通常会得到包含_time、_machine、_inc和_new的格式。为了得到MongoDB标准的_id格式(即{"$oid": "xxxx"}),你需要创建一个实现TypeAdapter的ObjectIdTypeAdapter,并将其注册到GsonBuilder。通过这个适配器,可以确保 ObjectId 在序列化和反序列化时保持正确格式。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值