使用嵌入式 JanusGraph,我正在创建一个返回 Vertex 和 Edge 列表的 REST 服务,但我想返回 json,就像 gremlin 服务器一样。
我尝试使用 MessageSerializer,但无法将二进制格式强制转换为 json。
@RequestMapping("/search")
public String search(@RequestBody SearchOptions options) throws JsonProcessingException, SerializationException {
List<Object> data = new ArrayList<>();
Builder responseBuilder = getResponseBuilder(data);
List<Vertex> nodes;
List<Object> edges;
if (Strings.isNullOrEmpty(options.getText()) || Strings.isNullOrEmpty(options.getField())) {
nodes = g.V().limit(options.getLimit()).toList();
edges = g.V().limit(options.getLimit()).aggregate("node").outE().as("edge").inV().where(P.within("node"))
.select("edge").toList();
} else {
nodes = g.V().has(options.getField(), options.getText()).toList();
edges = g.V().has(options.getField(), options.getText()).aggregate("node").outE().as("edge").inV()
.where(P.within("node")).select("edge").toList();
}
data.add(nodes);
data.add(edges);
ResponseMessage response = responseBuilder.create();
ByteBufAllocator allocator = new PooledByteBufAllocator();
ByteBuf byteBuffer = ser.serializeResponseAsBinary(response, allocator);
byte[] bytes = byteBuffer.array();
String str = new String(bytes);
return str;
}
@Bean
public MessageSerializer messageSerializer() {
GryoMapper.Builder kryo = GryoMapper.build().addRegistry(JanusGraphIoRegistry.getInstance());
MessageSerializer serializer = new GryoMessageSerializerV1d0(kryo);
return serializer;
}
我尝试使用杰克逊对象映射器,但得到这个错误 -
[http-nio-8080-exec-10] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
org.apache.tinkerpop.shaded.jackson.databind.JsonMappingException: (was java.lang.IllegalStateException) (through reference chain: org.apache.tinkerpop.gremlin.driver.message.ResponseMessage["result"]->org.apache.tinkerpop.gremlin.driver.message.ResponseResult["data"]->java.util.ArrayList[0]->java.util.ArrayList[0]->org.janusgraph.graphdb.relations.RelationIdentifier["inVertexId"])
at org.apache.tinkerpop.shaded.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:388)
我这样定义 ObjectMapper -
ObjectMapper mapper = GraphSONMapper.build().version(GraphSONVersion.V2_0).create().createMapper();
仅供参考 - 这是创建 ObjectMapper 的正确方法。
private ObjectMapper mapper = GraphSONMapper.build()
.addRegistry(JanusGraphIoRegistry.getInstance())
.version(GraphSONVersion.V2_0).create().createMapper();