假设有一个代码可以将多个日期变量变为:
Date dateVar1 = Date1;
Date dateVar2 = Date2;
Date dateVar3 = Date3;
我可以将这些日期作为JSON
返回,如下所示:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("dateVar1 =" + dateVar1 + "dateVar2 =" + dateVar2 + "dateVar3 =" + dateVar3);
但是这不能使用大量或动态数量的变量,所以我的问题是如何在这种情况下返回JSON响应?
答案 0 :(得分:1)
您可以使用jackson ObjectMapper将对象转换为JSON,反之亦然。
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(yourObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonString);