public class Crtl extends HttpServlet {
private static Log log = LogFactory.getLog(WacaiRemoteRequest.class);
private static ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//这里需要接受调用者传过来的json参数
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
写一个接口给别人调用,我需要接收到调用者传过来的json然后转换为list,再去调用另一个接口返回结果,请问怎样接收json?
package com.sample.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
public class SampleHttpServlet extends HttpServlet {
private static final long serialVersionUID = -2074707407667590820L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//用于接收对方的jsonString
StringBuilder jsonString = new StringBuilder();
BufferedReader reader = req.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
jsonString.append(line).append('\n');
}
} finally {
reader.close();
}
//doYourThings(jsonString.toString()) 继续做你的业务就可以了
}
}
json转换成字符串提交,后台再转换成json
为什么不用map接收呢
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.framework.exception.BusinessException;
public class JsonUtils{
private static final ObjectMapper mapper = new ObjectMapper();
/**
* json转换成map
* @author layson
* @param json
* @return
* @throws BusinessException
*/
public static Map<?, ?> json2Map(String json)throws BusinessException{
Map result = null;
try {
result = (Map)mapper.readValue(json, Map.class);
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(-1, "Json转换成Map时出现异常。", e);
}
return result;
}
}