找不到类型返回值的转换器:class org.json.JSONObject

Kar*_*yan 2 java rest elasticsearch spring-boot

正在编写 Spring Boot 休息服务,以根据 _id (来自 elastic search )从 elastic search 获取产品。我能够打印来自服务的响应,意味着服务能够获取但在转换为 JSONObject 以返回到 UI 时抛出以下错误

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

请在下面找到我的代码。

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您不需要将产品转换为 JSONObject,因为 Spring Boot 会自动进行序列化。只需将方法返回类型更改为Product并直接返回product即可。

示例和指南: https: //spring.io/guides/gs/rest-service/