我正在使用 play 2.4 并想在模型“用户”中设置一个参考对象“文档”。如果我遍历迭代器,我会收到以下错误:因此,如果我调用路由 /users,通常我应该得到一个包含所有用户对象和嵌入文档的 Json 列表。
[MarshallingException:无法将结果解组为类模型。用户来自内容 {“_id”:{“$oid”:“560969b4d4c6209ff2a1a973”},“name”:“Alexander Buder”,“documents”:[{“name”:“ Sample.pdf"} , { "name" : "Test.pdf"}]}]
模型用户
package models;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.jongo.MongoCollection;
import org.bson.types.ObjectId;
import uk.co.panaxiom.playjongo.PlayJongo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by abuder on 28.09.15.
*/
public class User {
public static MongoCollection users() {
return PlayJongo.getCollection("users");
}
@JsonProperty("_id")
private ObjectId id;
private String name;
private List<Document> documents = new ArrayList<Document>();
public User save() {
users().save(this);
return this;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Document> getDocuments() {
return documents;
}
public void setDocuments(List<Document> documents) {
this.documents = documents;
}
public void remove() {
users().remove(this.id);
}
public static User findByName(String name) {
return users().findOne("{name: #}", name).as(User.class);
}
public static List<User> findAll(){
List<User> userList = new ArrayList<User>();
Iterator<User> iterator = users().find().as(User.class).iterator();
while (iterator.hasNext()){
userList.add(iterator.next());
}
return userList;
}
}
模型文件
package models;
/**
* Created by abuder on 28.09.15.
*/
public class Document {
private String name;
public Document(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
控制器
package controllers;
import models.Document;
import models.User;
import play.*;
import play.libs.Json;
import play.mvc.*;
import views.html.*;
import java.util.List;
public class Application extends Controller {
public Result index() {
Document doc1 = new Document("Sample.pdf");
Document doc2 = new Document("Test.pdf");
User user = new User();
user.setName("Alexander Buder");
user.getDocuments().add(doc1);
user.getDocuments().add(doc2);
user.save();
return ok(Json.toJson(user));
}
public Result usersJson(){
List<User> userList = User.findAll();
return ok(Json.toJson(userList));
}
}
路线
GET / controllers.Application.index()
GET /users controllers.Application.usersJson()