IllegalStateException:期望一个字符串,但是第1行第2行路径$是BEGIN_OBJECT;嵌套异常是com.google.gson.JsonSyntaxException

问题描述 投票:1回答:1

我在Spring Boot中做了一个post请求并用postman测试它,但是当我在Postman中传递body并尝试在我的应用程序中读取它时,它会抛出错误。 这是Spring中的方法:

@PostMapping(path=PathConstants.START_ACTION)
    public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) String params){

if(params!=null) {
                Gson gson = new Gson();
                Map<String,Object> pvar = gson.fromJson(params, Map.class);
                System.out.println(pvar);           
            } 
}

在Postman中,我通过这种方式传递params:

enter image description here

我在标题中指定了内容类型为application/json。 但是,如果我使用“Param”标签传递我的参数

enter image description here

有用。但我需要将它们作为身体传递而不是传递。这里的问题在哪里?

spring-boot http-post postman post-parameter
1个回答
1
投票

方法1:

标题Content-Typeapplication-json。所以Spring尝试将你的json构建成LinkedHashMap

现在,试试这个......

@PostMapping(path=PathConstants.START_ACTION)
    public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) Map<String, Object> bodyObject){

if(MapUtils.isNotEmpty(bodyObject)) {
              Map<String,Object> pvar = bodyObject;
}

代替

@PostMapping(path=PathConstants.START_ACTION)
    public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) String params){

if(params!=null) {
                Gson gson = new Gson();
                Map<String,Object> pvar = gson.fromJson(params, Map.class);
                System.out.println(pvar);           
            } 
}

并通过header content-type作为application/json。这会工作..

方法2 ::

现在,如果您仍想使用自己的旧签名方法,请执行此操作。

 @PostMapping(path=PathConstants.START_ACTION)
        public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) String params){}

然后在header content-type作为text/plain。然后你的旧方法也会工作..

© www.soinside.com 2019 - 2024. All rights reserved.