首页 > 代码库 > Httpservlet 获取json对象字符窜

Httpservlet 获取json对象字符窜

使用的是google 的json转换jar

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.apache.commons.io.IOUtils;

 

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
    

  //输入流的方式获取数据(自能获取一次) 

     //前端传来的数据为 {"act":1,"userinfo":{"nickname":"耐心"}}
        String requestStr = IOUtils.toString(request.getInputStream(), "UTF-8");
 
        JsonParser parser = new JsonParser();
        JsonObject root = parser.parse(requestStr).getAsJsonObject();

   int act = root.get("act").getAsInt();

      JsonObject userinfo = root.get("userinfo").getAsJsonObject();
          String Nickname=userinfo.get("nickname").getAsString());

}

 

Httpservlet 获取json对象字符窜