how to serialize class?

后端 未结 8 1926
自闭症患者
自闭症患者 2021-01-11 19:28

When I insert a List into mongodb, there is a problem:

Exception in thread \"main\" java.lang.IllegalArgumentException: can\'t serialize class mongodb.Person         


        
相关标签:
8条回答
  • 2021-01-11 20:30

    Your Person class definition needs to have implements Serializable in order for it to be serialized, e.g.:

    class Person implements Serializable {
       //Rest here
    }
    

    Here are some useful links on Java object serialization: Link, Link.

    0 讨论(0)
  • 2021-01-11 20:31

    The problem here not in "implements Serializable". The problem is that object not converted in the DBObject.

    Possible solution:

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.mongodb.*;
    
    ....
    
    ObjectMapper mapper = new ObjectMapper();
    DBObject dboJack = mapper.convertValue(new Person("Jack"), BasicDBObject.class);
    ...
    
    0 讨论(0)
提交回复
热议问题