【发布时间】:2014-01-30 09:49:09
【问题描述】:
在我的 Java Play 框架应用程序中,我想将 ArrayList 值存储在 mongoDB 中。
我在 JSON 中有 3 个值,即 loginid、电话、学生;在那个学生中是 ArrayList。我将数据存储在 mongoDB 中,如下所示:
{ "loginid" : "user@mail.com", "phone" : "0123456789", "students" : [{"firstName" : "Jesse", "lastName" : "Varnell", "age" : "15", "gender" : "M" }, { "firstName" : "John", "lastName" : "Doe", "age" : "13", "gender" : "F"}] }
我正在使用 mongo 查询来存储以下值:
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject theUserObj = new BasicDBObject();
ArrayList<Student> student = new ArrayList<Student>();
if(studentArray != null && studentArray.size()>=0) {
Student stud = new Student();
for(int i = 0; i < studentArray.size(); i++){
stud = studentArray.get(i);
student.add(stud);
}
}
theUserObj.put("loginid", profile.loginid);
theUserObj.put("phone", profile.phone);
searchQuery.append("loginid", username);
theUserObj.put("students", student);
theUserCollection.update(searchQuery, theUserObj); //Got error on this line.
我收到以下错误:
Execution exception (In /app/controllers/StudentInfo.java around line 176)
IllegalArgumentException occured : can't serialize class models.Student
play.exceptions.JavaExecutionException: can't serialize class models.Student
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:237)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.IllegalArgumentException: can't serialize class models.Student
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.update(DBApiLayer.java:346)
at com.mongodb.DBCollection.update(DBCollection.java:165)
at com.mongodb.DBCollection.update(DBCollection.java:197)
at com.mongodb.DBCollection.update(DBCollection.java:209)
at controllers.StudentInfo.doStoreProfile(StudentInfo.java:176)
at controllers.StudentInfo.storeUserProfile(StudentInfo.java:212)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:557)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:508)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:484)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:479)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161)
如何使用 Java 在 MongoDB 中使用 ArrayList 存储值?
【问题讨论】:
-
你的
Student类实现了Serializable吗? -
没有。它是 Model in Play 框架之一。
-
你能编辑这个类吗?尝试使其实现 Serializable/
-
是的。让我现在试试。
-
试过了,还是一样的错误。
标签: java mongodb arraylist playframework