简体   繁体   中英

No converter found for return value of type: class org.json.JSONObject

Am writing Spring Boot rest service to get products from elastic search based on _id ( from elastic search ). Am able to print the response from the service, means service able to fetch but while converting to JSONObject to return back to UI its throwing below error

No converter found for return value of type: class org.json.JSONObject

Please find my code below.

public JSONObject getProductById(String id){

    String[] includes = new String[]{id};
    String[] excludes = Strings.EMPTY_ARRAY;
    GetRequest getRequest = new GetRequest(INDEX, TYPE, SOURCE);
    getRequest.routing(id);

    GetResponse getResponse = null;
    try {
        getResponse = restHighLevelClient.get(getRequest);
    } catch (java.io.IOException e){
        e.getLocalizedMessage();
    }

    //GetResponse getResponse = null;

    // create the search request
    SearchRequest searchRequest = new SearchRequest(INDEX); 
    searchRequest.types(TYPE);

    // create the match query on the author field
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("_id", id); 
    searchSourceBuilder.query(matchQueryBuilder); 
    searchRequest.source(searchSourceBuilder);

    // send the request
    SearchResponse searchResponse = null;
    try {
         searchResponse = restHighLevelClient.search(searchRequest);
         logger.info("response ---->"+searchResponse);
    } catch (IOException e) {
        e.getLocalizedMessage();
    }
    // read the response
    String productName = null;
    Product product = null;
    SearchHit[] searchHits = searchResponse.getHits().getHits();
    for (SearchHit hit : searchHits) {
        // get each hit as a Map
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        product=new Product();
        product.setName(sourceAsMap.get("name").toString());
        /*productName = (String) sourceAsMap.get("name");*/

    }

    Gson gson=new Gson();
    JSONObject productJSON = null;
    String prodStr=gson.toJson(product);
    try {
        productJSON=new JSONObject(prodStr);
    } catch (JSONException e) { 
        e.printStackTrace();
    }
    return productJSON;
}

You do not need to convert the product to JSONObject as Spring Boot does the serialization automatically. Just change method return type to Product and directly return product .

Example & Guide: https://spring.io/guides/gs/rest-service/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM