How to clear ClassCastException in java?

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

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

Error: Exception in thread "main" java.lang.ClassCastException: 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?

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:

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.

1 Like