找不到类型为:class org.json.JSONObject

时间:2018-05-23 13:45:42

标签: java rest spring-boot elasticsearch

我正在编写Spring Boot rest服务,以便根据_id(来自弹性搜索)从弹性搜索中获取产品。能够从服务打印响应,意味着服务能够获取但在转换为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;
}

1 个答案:

答案 0 :(得分:2)

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

示例&amp;指南:https://spring.io/guides/gs/rest-service/