[英]OrientDB serialize a query result directly to Json
I have a orient db query and want to pass the result back as json. 我有一个东方的数据库查询,并希望将结果传回json。 So I have the following code:
所以我有以下代码:
OSQLSynchQuery<ODocument> q = new OSQLSynchQuery<ODocument>(query);
List<ODocument> result = db.command(q).execute();
return new ObjectMapper().writeValueAsString(result);
But since the serialization of ODocument leads to an infinite recursion ( see this SO question ) I have a problem. 但是由于ODocument的序列化会导致无限递归( 请参见此SO问题 ),所以我遇到了问题。
Looping the list and concatinating ODocument#toJSON() to a StringBuffer is not my prefered option. 循环列表并将ODocument#toJSON()复制为StringBuffer不是我的首选。 Especially since I also have a case where I transform a "group by" result into a hashmap which I want to be json too.
特别是因为我也有将“分组依据”结果转换为也希望成为json的hashmap的情况。 So is there a clean way on json serializing ODcomument as part of another object (list or map)?
那么在JSON序列化ODcomument作为另一个对象(列表或映射)的一部分上,有没有一种干净的方法?
This is for sure not a very nice way but this is working quite well. 当然,这不是一个很好的方法,但是效果很好。 First I loop through the result and build a list of json strings:
首先,我遍历结果并构建一个json字符串列表:
List<String> jsonResult = new ArrayList<>();
for (ODocument d : queryResult) jsonResult.add(d.toJSON());
Next I have made a custom serializer which is just writing the raw string (json) to the buffer: 接下来,我做了一个自定义的序列化程序,它只是将原始字符串(json)写入缓冲区:
public class RawJsonListJacksonSerializer extends JsonSerializer<List<String>> {
@Override
public void serialize(List<String> entries, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeStartArray();
for (int i=0; i<entries.size(); i++) {
jsonGenerator.writeRaw(entries.get(i) == null ? "null" : entries.get(i));
if (i<entries.size()-1) jsonGenerator.writeRaw(",");
}
jsonGenerator.writeEndArray();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.