Struts2接口接收Json参数

Struts2接口接收Json参数

1、编写工具类获取json对象

import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 获取取请求中Josn传输数据
 */
public class RequestJsonDateUtils {

    //获取请求体中的数据
    public  static String  getRequestJsonStr() {
        HttpServletRequest request = ServletActionContext.getRequest();
        InputStream inputStream;
        String strResponse = "";
        try {
            inputStream = request.getInputStream();
            String strMessage = "";
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            while ((strMessage = reader.readLine()) != null) {
                strResponse += strMessage;
            }
            reader.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strResponse;
    }
}
var foo = 'bar';

2、具体方法中调用

/**
 * 测试方法
 * @throws BaseException
 * @throws Exception
 */
public void sign() throws BaseException, Exception {
    if(testPO==null){
        //获取请求体中内容,转换为json
        JSONObject jsonRequest = JSONObject.fromObject( RequestJsonDateUtils.getRequestJsonStr());
        testPO = new TestPO();
        testPO.setIdcard(jsonRequest.containsKey("testPO.idcard")?jsonRequest.getString("testPO.idcard"):null);
        testPO.setRefCompName(jsonRequest.containsKey("testPO.refCompName")?jsonRequest.getString("testPO.refCompName"):null);
        testPO.setRefCompId(jsonRequest.containsKey("testPO.refCompId")?jsonRequest.getString("testPO.refCompId"):null);
        testPO.setSkillsHobbies(jsonRequest.containsKey("testPO.skillsHobbies")?jsonRequest.getString("testPO.skillsHobbies"):null);
        testPO.setWorkUnit(jsonRequest.containsKey("testPO.workUnit")?jsonRequest.getString("testPO.workUnit"):null);
        testPO.setPos(jsonRequest.containsKey("testPO.pos")?jsonRequest.getString("testPO.pos"):null);
        testPO.setIsNewMember(jsonRequest.containsKey("testPO.isNewMember")?jsonRequest.getString("testPO.isNewMember"):null);
    }
    this.memberSignService.sign(this.testPO); //调用service层
}

你可能感兴趣的:(java,struts2,json,java,接口)