java中json接受接口_java接口接受json

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值