我的简单应用程序假设只使用_id
到user
之间的映射填充MongoDB。我的密钥(_id
)采用JSON格式,其值只有很长。
{
"_id": {
"a": "1B2ac",
"b": "Windows NT 5.2; WOW64; rv:16.0 Ff/6.0"
},
"user": 1999129
}
我有几个问题:
问题1:当我尝试插入时,我得到can's serialize class...
:
Caused by: java.lang.IllegalArgumentException: can't serialize class test.mongo.foo.DummyObject
at org.bson.BSONEncoder._putObjectField(BSONEncoder.java:234)
at org.bson.BSONEncoder.putObject(BSONEncoder.java:121)
at org.bson.BSONEncoder.putObject(BSONEncoder.java:86)
at com.mongodb.OutMessage.putObject(OutMessage.java:190)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:253)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:217)
at com.mongodb.DBCollection.insert(DBCollection.java:102)
at com.test.mongo.foo.DaoImpl.insertRecords(DaoImpl.java:130)
以下是DummyObject
(实现Serializable
)的课程:
package test.mongo.foo;
import java.io.Serializable;
public class DummyObject implements Serializable{
private static final long serialVersionUID = -2715467675581503964L;
//default constructor
public DummyObject(){
}
private String a;
private String b;
public String getA() {
return a;
}
public String getB() {
return b;
}
public void setA(String a) {
this.a = a;
}
public void setB(String b) {
this.b = b;
}
}
这是我的DaoImp
班级
package test.mongo.foo;
public class DaoImpl extends MongoDAOImpl{
public int insertRecords(List<DBObject> records) {
DBCollection coll = getDBCollection();
Exception e = null;
try {
WriteResult res = coll.insert(records);
if (res.getError() != null) {
throw new MongoRuntimeException(res.getError());
}
return res.getN();
} catch (Exception err) {
e = err;
throw new MongoRuntimeException(err);
}
}
public static DBObject convertToDBObject(DummyObject obj, long value) {
DBObject bdbo = new BasicDBObject();
bdbo.put("_id",obj);
bdbo.put("user",value);
return bdbo;
}
public static void main(String [] args){
DummyObject d = new DummyObject();
d.setA("1B2ac");
d.setB("Windows NT 5.2; WOW64; rv:16.0 Ff/6.0");
long val = 1999129;
List<DBObject> l = new ArrayList<DBObject>();
l.add(DaoImpl.convertToDBObject(d,val));
DaoImpl impl = new DaoImpl();
}
}
问题2:为了避免上述问题,我尝试使用String to String mapping插入记录。虽然我的输入字符串(对于_id
)没有被转义,但DBObject
在内部转义它并最终写入MongoDB,如下所示:
{
"_id": {
\"a\": \"1B2ac\",
\"b\": \"WindowsNT5.2;WOW64;rv: 16.0Ff/6.0\"
},
"user": NumberLong(1999129)
}
INSTEAD OF
{
"_id": {
"a": "1B2ac",
"b": "Windows NT 5.2; WOW64; rv:16.0 Ff/6.0"
},
"user": 1999129
}
有关如何解决这两个问题的任何建议?任何指针都非常受欢迎。
答案 0 :(得分:2)
没关系。在玩了一下之后,我找到了回答我自己的问题。作为JsonObject插入。我将我的DummyObject转换为JsonObject / Object(提示:Json.parse(jstr))
由于 Masti