我是从 Python 转过来的 Java 新手,我正在尝试弄清楚如何循环 ebean 查询结果集并将数据附加到 JSON 对象,该对象将被发送回前端的自动完成小部件。
我正在使用以下库:
- 导入 com.fasterxml.jackson.databind.ObjectMapper;
- 导入 com.fasterxml.jackson.databind.node.ObjectNode;
目前搜索确实有效,但如果有多个结果我只得到一个,我怀疑这是因为我每次通过循环都覆盖了我的 JSON 对象。
JSON 对象上的 .putArray 方法每次都会将其清除吗?如果是这样,我应该如何将 JSON 对象附加到已经存在的 JSON 数组中。
我的自动完成方法:
@Security.Authenticated(Secured.class)
public Result searchContacts(String term) {
List<Contact> searchedContacts = Contact.find.where().eq("firm_id", session().get("firm")).or(com.avaje.ebean.Expr.like("first_name", "%"+ term + "%"),
com.avaje.ebean.Expr.like("last_name", "%" + term + "%")).findList();
// build result set for autocomplete suggesstions
ObjectNode suggestion = Json.newObject();
for (Contact contact: searchedContacts) {
ObjectNode result = Json.newObject();
result.put("value", contact.firstName + ' ' + contact.lastName);
result.put("data", contact.id);
suggestion.putArray("suggestions").add(result);
}
return ok(suggestion);
}
JSON 结构必须如下所示:
suggestions: [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
最佳答案
你需要将所有建议收集到某个集合中,即com.fasterxml.jackson.databind.node.ArrayNode
,然后用它创建一个JSON对象,这个片段给你你想要的(当然我假设您的数据库查询返回有效的数据集):
public Result searchContacts(String term) {
List<Contact> searchedContacts = Contact.find.where()
.eq("firm_id", session().get("firm"))
.or(com.avaje.ebean.Expr.like("first_name", "%"+ term + "%"),
com.avaje.ebean.Expr.like("last_name", "%" + term + "%"))
.findList();
ArrayNode suggestions = Json.newArray();
for (Contact contact : searchedContacts) {
ObjectNode result = Json.newObject();
result.put("value", contact.firstName + ' ' + contact.lastName);
result.put("data", contact.id);
suggestions.add(result);
}
ObjectNode output = Json.newObject();
output.set("suggestions", suggestions);
return ok(output);
}
关于java - Play Framework Java - 构建嵌套 JSON 对象以进行自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502809/