问题
How do I specify the SolrQuery to return the data in json format? Heres the code I am using to query data: Once I get the SolrDocument how can I convert it to a json Object/string?
SolrQuery sQuery = new SolrQuery();
sQuery.setQuery("name:test");
QueryResponse resp = server.query(sQuery);
SolrDocumentList docs = resp.getResults();
回答1:
SolrJ is designed to retrieve/convert the document as your defined POJO. If you want to convert the document to JSON, you would need to use a library like Jackson to do the conversion from SolrDocument to JSON.
Not sure if this would be an option for you, but wanted to mention that you might consider getting the response from Solr already formatted as JSON. See SolJSON for more details. You would not need to use SolrJ in this case. The easiest thing would be to use a straight http call (via a java http client library) and get a JSON response back from Solr using the SolJSON techniques.
回答2:
Import the JSONUtil class from solrj, it has json converter for solr documents or you can write one easily if you see the code of that class:
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
回答3:
You can also do it using GSON.
SolrDocumentList SolrResponse = searchWithSolr();
Gson gson = new Gson();
if (SolrResponse.size()!=0) {
System.out.println(gson.toJson(SolrResponse));
interpolMap.put("interpol", gson.toJson(InterpolSolrResponse));
}
来源:https://stackoverflow.com/questions/13011637/using-solrj-to-retrieve-a-solrdocument-in-json-format