我有一个动态web项目,在我的jsp页面中,单击表单时,它将从elasticsearch中检索数据,并以正确的json格式显示在UI中显示为Key:值对。如何将输出格式化为正确的json格式?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start = request.getParameter("start");
String end = request.getParameter("end");
String line1;
StringBuffer jsonString1 = new StringBuffer();
try {
URL url1 = new URL("http://localhost:9200/indexname/_search?filter_path=hits.hits._source&pretty=1&size=100000");
String payload1 = "{\"query\":{\"filtered\":{\"filter\":{\"range\":{\"Date\":{\"lte\":\""+end+"\",\"gte\":\""+start+"\"}}}}},\"_source\":{\"include\":[\"ID\",\"Name\",\"Status\",\"Date\"]}}";
HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection();
connection1.setDoInput(true);
connection1.setDoOutput(true);
connection1.setRequestMethod("POST");
connection1.setRequestProperty("Accept", "application/json");
connection1.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer1 = new OutputStreamWriter(connection1.getOutputStream(), "UTF-8");
writer1.write(payload1);
writer1.close();
BufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
while ((line1 = br1.readLine()) != null) {
jsonString1.append(line1);
}
br1.close();
file1.close();
connection1.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
response.setContentType("application/json");
// JSONObject jsonObj = new JSONObject(jsonString1.toString()); //JSONObject cannot be resolved to a type error is getting displayed.
//System.out.println("---------------------------");
// System.out.println(jsonObj);
PrintWriter out = response.getWriter();
out.print(jsonString1); //Here instead of String buffer I want to send a json object or an arraylist which outputs just the key value pair by removing all unwanted characters.
out.flush();
out.close();
}
并购HTML,在执行提交操作,它显示是这样的:
{ "hits" : { "hits" : [ { "_source":{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"} }, { "_source":{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"} }, { "_source":{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"} }, { "_source":{"ID":"126","Status":"false","Name":"TYT_333","Date":"2010-08-16T12:06:48"} }, { "_source":{"ID":"127","Status":"false","Name":"CVF_230","Date":"2010-08-16T12:07:18"} }, { "_source":{"ID":"128","Status":"true","Name":"AWE_101","Date":"2010-08-16T12:03:48"} }, { "_source":{"ID":"129","Status":"true","Name":"WEC_299","Date":"2010-08-16T12:07:29"} } ] }}
相反,我想这样的地方显示
在我的UI显示一些警告框或东西{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"},
{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"},
{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"}
等....
我如何能做到这一点任何想法?请指教。谢谢。
'org.json'是一个很好的方法来做到这一点。如果您有错误,请尝试将其二进制文件添加到您的JSP类路径中。这应该做的伎俩。 –