Java – how to serialize classes?
•
Java
When I insert the 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 procedure 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 Google's answer, so please help me
Solution
You only need to implement the serializable interface in the person class
It is also good to define a serialVersionUID in your class
AFAIK, when creating a POJO class in Java, the class should be serializable. If it is to be transmitted through some streams, it has a default constructor and allows the use of getter and setter methods to access properties / fields
You may be interested in reading: discover the secrets of the Java serialization API
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码