# Elasticsearch json response to SearchResponse object

**URL:** <https://discuss.elastic.co/t/elasticsearch-json-response-to-searchresponse-object/124394>\
**Category:** Elasticsearch\
**Created:** [March 17, 2018, 9:20am UTC](https://discuss.elastic.co/t/elasticsearch-json-response-to-searchresponse-object/124394 "2018-03-17T09:20:06Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Monte\_A](https://avatars.discourse-cdn.com/v4/letter/m/34f0e0/32.png) [@Monte\_A](https://discuss.elastic.co/u/Monte_A)\
**Post date:** [March 18, 2018, 3:14pm UTC](https://discuss.elastic.co/t/elasticsearch-json-response-to-searchresponse-object/124394/6 "2018-03-18T15:14:43Z")

</div>

Working solution for someone that might have the same issue.

**Elasticsearch response with aggregation example:**

> <https://gist.github.com/anonymous/cd2de1ccdedf072f40b69b9094afa05e>

**Helper method to create NamedXContentRegistry**

```
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;
}

```

**Method to get SearchResponse from String/Json**

```
public static SearchResponse getSearchResponseFromJson(String jsonResponse){
    try {
        NamedXContentRegistry registry = new NamedXContentRegistry(DashboardCuke.getDefaultNamedXContents());
        XContentParser parser = JsonXContent.jsonXContent.createParser(registry, jsonResponse);
        return SearchResponse.fromXContent(parser);
    } catch (IOException e) {
        System.out.println("exception " + e);
    }catch (Exception e){
        System.out.println("exception " + e);
    }
    return new SearchResponse();
}
```

---

_[View the full topic](https://discuss.elastic.co/t/elasticsearch-json-response-to-searchresponse-object/124394)._
