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)
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;
}
}
The program is :
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);
I can't find the answer from google, so please help me.
class Person should implement
java.io.Serializable
interface.class Person implements Serializable
First of all you should know why you make class Serializable? Whenever you want to move obeject on network to a file, database, network, process or any other system. In java simple Implementation. Just Implement Serializable interface.
Just implement Serializable interface in Person class.
Also it will be good to define a
serialVersionUID
in your class.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.
You might be interested in reading this: Discover the secrets of the Java Serialization API
I got the same exception while working with mongodb. I tried making the problematic class serializable but that didn't fix my problem.
Following is what worked for me. Extend the class to be a child of BasicDBObject . Of course this works only if the problem is caused by MongoDB.
Original source
http://techidiocy.com/cant-serialize-class-mongodb-illegal-argument-exception/#comment-1298
The problem here not in "implements Serializable". The problem is that object not converted in the DBObject.
Possible solution:
Your
Person
class definition needs to haveimplements Serializable
in order for it to be serialized, e.g.:Here are some useful links on Java object serialization: Link, Link.