将Json字符串传递给Spring Controller

时间:2018-06-15 07:05:30

标签: java json spring spring-mvc controller

我想传递并从控制器获取Json字符串。 我想通过传递json String来调用控制器,并且还希望在Controller中获取json String。 有没有办法做到这一点。 我的url参数中有2个值:: api = asdf23&& jsonstr = {" name":" myname"," age":" 20"} 如何在控制器上获得这两个参数

@RequestMapping(value = "/GetJSON", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody String GetJSON(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "api") String apiKey,
            @RequestParam(value = "jsonstr") String json)
            throws ParseException {
        System.out.println("JSON :: "+json);
        return json;
    }

5 个答案:

答案 0 :(得分:1)

创建一个具有2个属性名称和年龄

的pojo
public class Test{
private String name;
private Integer age;
//getter and setters
}

然后修改你的控制器以接受requestbody中的json并将请求方法更改为post

@RequestMapping(value = "/GetJSON", method = RequestMethod.POST, produces = "application/json")

public @ResponseBody String GetJSON(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "api") String apiKey,
            @RequestBody Testjson testJson)
            throws ParseException {

答案 1 :(得分:1)

我建议不要使用URL参数来传递整个JSON对象,而是使用POST方法并将JSON放在正文中。但是,如果您有理由使用GET和json作为url参数,请从此链接获取正确的encode Http URL帮助。

对于您的情况,您的JSON对象将如下所示: api%3Dasdf23%26jsonstr%3D%7B%22name%22%3A%22myname%22%2C%22age%22%3A%2220%22%7D

答案 2 :(得分:0)

api = asdf23 **&& ** jsonstr = {“name”:“myname”,“age”:“20”}

您只需要一个&

答案 3 :(得分:0)

你也可以使用gson 2.2.2 jar

RequestMapping(value = "/GetJSON", method = RequestMethod.GET)
public @ResponseBody String GetJSON(
        HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "api") String apiKey)
        throws ParseException {
      Gson gson=new Gson();

      Emp emp=new Emp();
        String  json =gson.tojson(emp);


    System.out.println("JSON :: "+json);
    return json;
}`

答案 4 :(得分:0)

传递JSON HTTP请求

  1. 使用正文作为POST请求。
  2. 使用url编码。
  3. 以下仅举例:

    jsonstr = { “名称”: “MYNAME”, “年龄”: “20”} url:80 / GetJSON?jsonstr =%7B%22name%22%3A%22myname%22%2C%22age%22%3A%2220%22%7D

    有关URL编码的更多信息,请参阅下面的

      

    百分比编码,也称为URL编码,是一种机制   在统一资源标识符(URI)下编码信息   某些情况下。虽然它被称为URL编码,但它在   事实上,更常用于主要的统一资源标识符   (URI)集,包括统一资源定位符(URL)和   统一资源名称(URN)。因此,它也用于   准备application / x-www-form-urlencoded媒体的数据   类型,通常用于在HTTP中提交HTML表单数据   请求。

    https://en.wikipedia.org/wiki/Percent-encoding