如何序列化类? [英] how to serialize class?
问题描述
当我在mongodb中插入一个列表时,出现了一个问题:
When I insert a List into mongodb, there is a problem:
Exception in thread "main" java.lang.IllegalArgumentException: can't serialize class mongodb.Person
at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:234)
at org.bson.BasicBSONEncoder.putIterable(BasicBSONEncoder.java:259)
at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:198)
at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:140)
at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:86)
at com.mongodb.DefaultDBEncoder.writeObject(DefaultDBEncoder.java:27)
at com.mongodb.OutMessage.putObject(OutMessage.java:142)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:252)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:211)
at com.mongodb.DBCollection.insert(DBCollection.java:57)
at com.mongodb.DBCollection.insert(DBCollection.java:87)
at com.mongodb.DBCollection.save(DBCollection.java:716)
at com.mongodb.DBCollection.save(DBCollection.java:691)
at mongodb.MongoDB.main(MongoDB.java:45)
Person类的定义如下:
the class Person is defined as follows:
class Person{
private String name;
public Person(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
程序为:
DBCollection coll = db.getCollection("test");
DBObject record = new BasicDBObject();
List<Person> persons= new ArrayList<Person>();
persons.add(new Person("Jack"));
record.put("person", persons);
coll.save(record);
我找不到来自Google的答案,所以请帮助我.
I can't find the answer from google, so please help me.
推荐答案
只需实现可序列化接口.
另外,在您的课程中定义一个serialVersionUID
也很好.
Also it will be good to define a serialVersionUID
in your class.
AFAIK,在用Java创建POJO类时,该类应该是可序列化的,如果要通过某个流进行传输,它具有默认构造函数,并允许使用getter和setter方法访问属性/字段.
AFAIK, while creating POJO class in java, the class should be serializable, if it is going to be transfered over some stream, have a default constructor, and allows access to properties/fields using getter and setter methods.
您可能有兴趣阅读以下内容:发现Java序列化API的秘密
You might be interested in reading this: Discover the secrets of the Java Serialization API
这篇关于如何序列化类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!