我想返回 N1qlQueryResult
作为我的 REST API
的响应。下面是代码:
@RequestMapping(value = "/test", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<?> get() {
List<N1qlQueryRow> result = null;
try {
Cluster cluster = CouchbaseCluster.create("localhost");
Bucket bucket = cluster.openBucket("myBucket", "xyz");
bucket.bucketManager().createN1qlPrimaryIndex(true, false);
N1qlQueryResult queryResult = bucket.query(N1qlQuery.simple("select * FROM myBucket"));
queryResult.forEach(System.out::println);
result = queryResult.allRows();
} catch (final Exception exception) {
exception.printStackTrace();
}
return ResponseEntity.ok(result);
}
我收到错误消息:
Could not write content: No serializer found for class com.couchbase.client.java.query.DefaultN1qlQueryRow and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.couchbase.client.java.query.DefaultN1qlQueryRow and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0])
解决办法是什么?我想以 JSON
形式返回响应。
最佳答案
ObjectMapper
默认情况下,当 bean 为 empty
时失败。我们可以像下面这样禁用它:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
但在你的情况下它不能解决问题,因为结果无论如何都是空的。返回没什么好主意type
-s 不代表POJO
本身。 N1qlQueryResult
和DefaultAsyncN1qlQueryRow
没有经典getters
和Jackson
无法识别类似的方法 value()
默认情况下。我建议创建Map<String, Object>
并构建所需的输出并手动包含所需的属性:
Map<String, Object> n1QlResult = new HashMap<>();
n1QlResult.put("status", result.status());
// other ...
n1QlResult.put("rows", result.allRows()
.stream()
.map(i -> i.value().toMap())
.collect(Collectors.toList()));
最后返回:
return ResponseEntity.ok(n1QlResult);
当然,当你有很多这样的方法时,你可以编写公共(public)层将这些类型的对象转换为 Map
或编写自定义序列化程序并配置 ObjectMapper
用户 Spring
容器。
编辑
如果您只想返回行,请返回:
result.allRows()
.stream()
.map(i -> i.value().toMap())
.collect(Collectors.toList())
关于java - 如何返回 N1ql 查询结果作为 Couchbase 数据库的 REST API 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55179768/