将BSON类型ObjectId转换为JSON(存储在Mongodb中)-Java [英] Converting BSON Type ObjectId to JSON (Storing in Mongodb) -Java
问题描述
new Gson()。toJson(new ObjectId())
当我执行上述操作时,我得到的输出是
_ id:{_time:1374347520,_machine:-1025067326,_inc:585905201,_new:false} b
但其实我希望它是
_ id: {$ oid:51eae100c2e6b6c222ec3431}
这是通常的mongodb ID格式。什么是Java的这个更好的方法?
更新:
我的价值对象
import com.google.gson.annotations.SerializedName;
import org.bson.types.ObjectId;
public class TaskObject {
@SerializedName(_ id)
private ObjectId _id;
@SerializedName(revNo)
private int revNo;
}
我试图用自定义_id将它存储到mongodb中
TaskObject taskObject = new TaskObject();
taskObject.set_id(new ObjectId());
TaskMongoDBClient.getInstance()。
persistNewTaskData(new Gson()。toJson(taskObject));
存储在mongodb中的内容如下所示。
_id:{_time:1397464341,_machine:1441187434,_inc:-1687457948,_new:true}
而不是_id:{$ oid:xxxx},我可以通过使用oid值来查询。
我在这里做错了什么?请帮助。
谢谢
至少有两种可能如何做到这一点。可能最正确的方法是使用GSON TypeAdapter 来配置ObjectId如何写入(并从中读取)JSON。你需要创建一个实现 TypeAdapter
的东西,并用 GsonBuilder
注册它,这样GSON知道有一种特殊的方法处理ObjectIds。
我写了一个小测试来证明这一点,使用您的用例和示例对象(但省略了 请注意,测试声明JSON看起来像您想要它,并且我必须创建知道ObjectId的字段名称为$ oid的 还要注意,如果更改对象写入JSON的方式,则还需要更改其读取方式。所以我还实现了 在现实生活中,您也可能希望在这两种情况下检查空值。 / p> 因为我是一名负责任的编码员,所以我也写了一个测试来显示阅读案例: 延伸阅读: 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 I am trying to store this to mongodb with a custom _id What is stored in the mongodb looks like this. _id: { "_time" : 1397464341 , "_machine" : 1441187434 , "_inc" : -1687457948 , "_new" : true} Instead of _id:{"$oid": xxxx} which i can query by using a the oid value. What I am doing wrong here? please help. Thanks There are at least two possible ways to do this. Probably the most correct way is to use the GSON TypeAdapter to configure how the ObjectId is written to (and read from) JSON. You need to create something that implements I've written a small test to prove this works, using your use case and example object (but omitted the Note that the test asserts the JSON looks the way you want it to, and that I had to create an Note also that if you change the way the object is written to JSON, you also need to change the way it's read. So I've also implemented In real life, you probably also want to check for null values in both of those cases too. Because I'm a responsible coder, I also wrote a test to show the reading case works too: Further reading: 这篇关于将BSON类型ObjectId转换为JSON(存储在Mongodb中)-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! revNo <
$ p $ @Test
public void shouldWriteCorrectJSON(){
//给出
TaskObject taskObject = new TaskObject();
taskObject._id = new ObjectId(51eae100c2e6b6c222ec3431);
Gson gson = new GsonBuilder()。registerTypeAdapter(ObjectId.class,new ObjectIdTypeAdapter())。create();
//当
时String gsonString = gson.toJson(taskObject);
//然后
assertThat(gsonString,is({\_id \:{\$ oid \:\51eae100c2e6b6c222ec3431\}} ));
}
private class ObjectIdTypeAdapter extends TypeAdapter< ObjectId> {
@Override
public void write(final JsonWriter out,final ObjectId value)throws IOException {
out.beginObject()
.name($ oid)
.value(value.toString())
.endObject();
$ b @Override
public ObjectId read(final JsonReader in)throws IOException {
in.beginObject();
assert$ oid.equals(in.nextName());
String objectId = in.nextString();
in.endObject();
返回新的ObjectId(objectId);
$ / code> ObjectIdTypeAdapter
,并且该值只是ObjectID的字符串值,并且不会单独对所有字段进行序列化。
read
来检查字段名称是否正确(如果它不正确,你应该在这里抛出一个Exception而不是使用简单的断言),然后读取该值并从此String值创建ObjectId。
@Test
public void shouldReadFromJSON(){
//给定
Gson gson = new GsonBuilder()。registerTypeAdapter(ObjectId.class,new ObjectIdTypeAdapter() )。创建();
//
时TaskObject actualTaskObject = gson.fromJson({\_id \:{\$ oid \:\51eae100c2e6b6c222ec3431 \} },TaskObject.class);
//然后
TaskObject taskObject = new TaskObject();
taskObject._id = new ObjectId(51eae100c2e6b6c222ec3431);
assertThat(actualTaskObject._id,is(taskObject._id));
}
import com.google.gson.annotations.SerializedName;
import org.bson.types.ObjectId;
public class TaskObject {
@SerializedName("_id")
private ObjectId _id;
@SerializedName("revNo")
private int revNo;
}
TaskObject taskObject = new TaskObject();
taskObject.set_id(new ObjectId());
TaskMongoDBClient.getInstance().
persistNewTaskData(new Gson().toJson(taskObject));
TypeAdapter
and register it with the GsonBuilder
, this way GSON knows there's a special way to handle ObjectIds.revNo
field for brevity):@Test
public void shouldWriteCorrectJSON() {
// given
TaskObject taskObject = new TaskObject();
taskObject._id = new ObjectId("51eae100c2e6b6c222ec3431");
Gson gson = new GsonBuilder().registerTypeAdapter(ObjectId.class, new ObjectIdTypeAdapter()).create();
// when
String gsonString = gson.toJson(taskObject);
// then
assertThat(gsonString, is("{\"_id\":{\"$oid\":\"51eae100c2e6b6c222ec3431\"}}"));
}
private class ObjectIdTypeAdapter extends TypeAdapter<ObjectId> {
@Override
public void write(final JsonWriter out, final ObjectId value) throws IOException {
out.beginObject()
.name("$oid")
.value(value.toString())
.endObject();
}
@Override
public ObjectId read(final JsonReader in) throws IOException {
in.beginObject();
assert "$oid".equals(in.nextName());
String objectId = in.nextString();
in.endObject();
return new ObjectId(objectId);
}
}
ObjectIdTypeAdapter
that knows the field name of ObjectId is "$oid" and the value is simply the string value of the ObjectID, and does not serialise all of the fields individually.read
to check that the field name is the correct one (you should probably throw an Exception here instead of using a simple assert if it's not correct), and then read the value and create the ObjectId from this String value.@Test
public void shouldReadFromJSON() {
// given
Gson gson = new GsonBuilder().registerTypeAdapter(ObjectId.class, new ObjectIdTypeAdapter()).create();
// when
TaskObject actualTaskObject = gson.fromJson("{\"_id\":{\"$oid\":\"51eae100c2e6b6c222ec3431\"}}", TaskObject.class);
// then
TaskObject taskObject = new TaskObject();
taskObject._id = new ObjectId("51eae100c2e6b6c222ec3431");
assertThat(actualTaskObject._id, is(taskObject._id));
}