我有来自elasticsearch rest客户端的json响应。我想从该字符串(json)创建elasticsearch SearchResponse或GetResponse对象,以便我可以重用grails-2.4.3 elasticsearch插件中的un-marshaling部分。有人可以帮助我吗?
答案 0 :(得分:1)
我不确定这个问题是否仍然相关,但这个问题对我有用:
String responseJson = "{\"took\":5,\"timed_out\":false,\"_shards\".....}";
try {
JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY,
new JsonFactory().createParser(responseJson));
SearchResponse response = SearchResponse.fromXContent(xContentParser);
...
Do Whatever
...
} catch (IOException e) {
handleException....
}
答案 1 :(得分:1)
我确实找到了可以帮助您的东西。
我写了这样的JSON:
XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
String result = Strings.toString(builder);
然后我想像这样阅读它:
try {
NamedXContentRegistry registry = new NamedXContentRegistry(getDefaultNamedXContents());
XContentParser parser = JsonXContent.jsonXContent.createParser(registry, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, result);
SearchResponse searchResponse = SearchResponse.fromXContent(parser);
} catch (IOException e) {
System.out.println("exception " + e);
} catch (Exception e) {
System.out.println("exception " + e);
}
public static List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
map.put(TopHitsAggregationBuilder.NAME, (p, c) -> ParsedTopHits.fromXContent(p, (String) c));
map.put(StringTerms.NAME, (p, c) -> ParsedStringTerms.fromXContent(p, (String) c));
List<NamedXContentRegistry.Entry> entries = map.entrySet().stream()
.map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey()), entry.getValue()))
.collect(Collectors.toList());
return entries;
}
希望它能起作用:)