ObjectId,在mongo中,存储的文档必须有一个"_id"键。这个键的值可以是任何类型的,默认是个ObjectId对象。
之前在把ObjectId类型的json格式转化成ObjectId时候报错。用的是fastjson工具,下面是main方法模拟的报错代码:
public static void main(String[] args) {
ObjectId id = ObjectId.get();
JSONObject jsonObject = (JSONObject)JSONObject.toJSON(id);
System.out.println("ObjectId的字符串形式:"+id.toString());
System.out.println("ObjectId的json形式:"+jsonObject);
//fastJson转化ObjectId
ObjectId o = (ObjectId)JSONObject.toJSON(jsonObject);
System.out.println("转换后的ObjectId的字符串形式"+o.toString());
}
运行main方法:
换一种转换格式,看看会不会报错:
public static void main(String[] args) {
ObjectId id = ObjectId.get();
JSONObject jsonObject = (JSONObject)JSONObject.toJSON(id);
System.out.println("ObjectId的字符串形式:"+id.toString());
System.out.println("ObjectId的json形式:"+jsonObject);
//fastJson转化ObjectId
ObjectId objectId = JSON.parseObject(jsonObject.toJSONString(), ObjectId.class);
System.out.println("转换后的ObjectId的字符串形式"+objectId.toString());
}
运行main方法:
可以看到代码本身并没有报错,但对比转换前后的数据,发现在转化后数据精度丢失,发生了改变,也不符合实际使用的要求。
解决办法:
替换fastjson,使用gson工具,再来看main方法:
public static void main(String[] args) {
ObjectId id = ObjectId.get();
String jsonString = JSONObject.toJSONString(id);
System.out.println("ObjectId的字符串形式:"+id.toString());
System.out.println("ObjectId的json形式:"+jsonString);
//Gson转化ObjectId
ObjectId objectId = new Gson().fromJson(jsonString, ObjectId.class);
System.out.println("转换后的ObjectId的字符串形式"+objectId.toString());
}
运行main方法:
可以看到,转换成功且数据没有发生变化。