有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用solrj检索json格式的SolrDocument

如何指定SolrQuery以json格式返回数据? 下面是我用来查询数据的代码:一旦我得到SolrDocument,我如何将其转换为json对象/字符串

 SolrQuery sQuery = new SolrQuery();
 sQuery.setQuery("name:test");
 QueryResponse resp = server.query(sQuery);
 SolrDocumentList docs = resp.getResults();

共 (3) 个答案

  1. # 1 楼答案

    从solrj导入JSONUtil类,它有用于solr文档的json转换器,或者如果看到该类的代码,您可以轻松编写一个:

    import org.apache.noggit.JSONUtil;
    
    SolrQuery sQuery = new SolrQuery();
    sQuery.setQuery("name:test");
    QueryResponse resp = server.query(sQuery);
    SolrDocumentList docs = resp.getResults();
    String returnValue = JSONUtil.toJSON(docs); //this has the json documents
    
  2. # 2 楼答案

    您也可以使用GSON

    SolrDocumentList SolrResponse = searchWithSolr();
    Gson gson = new Gson();
    if (SolrResponse.size()!=0) {
      System.out.println(gson.toJson(SolrResponse));
      interpolMap.put("interpol", gson.toJson(InterpolSolrResponse));
    }
  3. # 3 楼答案

    SolrJ旨在将文档检索/转换为您定义的POJO。如果要将文档转换为JSON,需要使用Jackson这样的库来完成从SolrDocument到JSON的转换

    不确定这是否是你的选择,但要提到的是,你可以考虑从已经被格式化为JSON的SOR中得到响应。有关更多详细信息,请参见SolJSON。在这种情况下,您不需要使用SolrJ。最简单的方法是使用直接的http调用(通过java http客户端库),并使用SolJSON技术从Solr获取JSON响应