java – 如何序列化类?

前端之家收集整理的这篇文章主要介绍了java – 如何序列化类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我将列表插入 mongodb时,有一个问题:
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定义如下:

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);

我找不到谷歌的答案,所以请帮助我.

解决方法

只需在Person类中实现 Serializable界面.

在你的类中定义一个serialVersionUID也是很好的.

AFAIK,在Java中创建POJO类时,类应该是可序列化的,如果要通过某些流传输,具有默认构造函数,并允许使用getter和setter方法访问属性/字段.

你可能有兴趣阅读:Discover the secrets of the Java Serialization API

原文链接:https://www.f2er.com/java/126432.html

猜你在找的Java相关文章