# How to clear ClassCastException in java?

**URL:** <https://discuss.elastic.co/t/how-to-clear-classcastexception-in-java/59841>\
**Category:** Elasticsearch\
**Created:** [September 6, 2016, 5:49am UTC](https://discuss.elastic.co/t/how-to-clear-classcastexception-in-java/59841 "2016-09-06T05:49:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![PriyaRajan](https://avatars.discourse-cdn.com/v4/letter/p/eada6e/32.png) [@PriyaRajan](https://discuss.elastic.co/u/PriyaRajan)\
**Post date:** [September 6, 2016, 5:49am UTC](https://discuss.elastic.co/t/how-to-clear-classcastexception-in-java/59841/1 "2016-09-06T05:49:40Z")

</div>

> public List query(){  
> List lineRange = new ArrayList();  
> Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch").build();  
> Client client = TransportClient.builder().settings(settings).build().addTransportAddress((TransportAddress) new InetSocketTransportAddress(new InetSocketAddress("127.0.0.1", 9300)));  
> SearchResponse sResponse = null;  
> QueryBuilder qb = QueryBuilders.rangeQuery("lineNumber").from(50).to(150);  
> sResponse = client.prepareSearch("jsonlogpage")  
> .setTypes("loglinenum")  
> .setQuery(qb)  
> .execute()  
> .actionGet();  
> for(SearchHit hit : sResponse.getHits()){  
> timeRange.add(hit); //add() shows error  
> }  
> i++;  
> }  
> return timeRange;  
> }

I'm using Search Response. I got an error in add().

Error: Exception in thread "main" java.lang.ClassCastException: org.elasticsearch.search.internal.InternalSearchHit cannot be cast to com.example.elasticsearch.LogLineEntry

LogLineEntry is a pojo class. My List is created for LogLineEntry, hit variable belongs to SearchHit. So I can't add searchHit variable into List. How can I resolve this?

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [September 6, 2016, 6:20am UTC](https://discuss.elastic.co/t/how-to-clear-classcastexception-in-java/59841/2 "2016-09-06T06:20:41Z")

</div>

SearchHit is an elasticsearch class. It describes a hit from which you can get the JSON Source document.  
You need to convert the JSON content to your Pojo.

You can use Jackson to deserialize from JSON to Pojo.

Something like:

```auto
ObjectMapper mapper = new ObjectMapper();
timeRange.add(mapper.readValue(hit.getSourceAsString(), LogLineEntry.class));

```

BTW If you are a Hibernate user, the latest versions of Hibernate do that also automatically.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:22pm UTC](https://discuss.elastic.co/t/how-to-clear-classcastexception-in-java/59841/3 "2017-07-05T22:22:24Z")

</div>


