【问题标题】:No converter found for return value of type: class org.json.JSONObject未找到类型返回值的转换器:类 org.json.JSONObject
【发布时间】:2018-11-02 13:01:13
【问题描述】:

正在编写 Spring Boot 休息服务,以基于 _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;
}

【问题讨论】:

    标签: java rest spring-boot elasticsearch


    【解决方案1】:

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

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

    【讨论】:

    • 太棒了......!..,我不知道这个......谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 2019-02-23
    • 2019-11-04
    • 2019-12-18
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多