Springboot中的json解析错误

Roo*_*eti 0 java spring-boot

我有一个简单的 springboot 程序,它接受一个 json 并打印它。主要目的是做 json 验证器包的使用,但当前的上下文是在基本的请求解析上。问题是当我尝试将输入请求映射到类实体时,它给出了以下错误:“org.springframework.http.converter.HttpMessageNotReadableException”,。

  • 控制器(Hello.java):

        @RequestMapping(method = RequestMethod.POST , consumes = "application/json")
        public ResponseEntity<String> welcome(
                @RequestBody DemoEntity demoEntity )
        {
            System.out.println(demoEntity.getName());
            String response ="success";
            return new ResponseEntity<>(response, HttpStatus.CREATED);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • Java 类实体:

    公共类 DemoEntity 实现了 Serializable {

        @JsonProperty("name")
        private String name;
        @JsonProperty("no")
        private int no;
    
        public int getNo() {
            return no;
        }
    
        public void setNo(int no) {
            this.no = no;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        DemoEntity(String name)
        {
            this.name = name;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
    • 完全异常:

    {“时间戳”:1497594485418,“状态”:400,“错误”:“错误请求”,“异常”:“org.springframework.http.converter.HttpMessageNotReadableException”,“消息”:“JSON解析错误:意外字符( '-'(代码 45))在数值中:预期数字 (0-9) 跟随减号,对于有效数值;嵌套异常是 com.fasterxml.jackson.core.JsonParseException:意外字符('-'(代码) 45)) 数值:预期数字 (0-9) 跟随减号,对于有效数值\n 在 [来源:java.io.PushbackInputStream@75be93a7; 行:1,列:3]","路径" : “/欢迎” }

正文中的示例输入请求:{"name":"Roopesh", "no":123123}

inv*_*nit 5

您发送了错误的请求。使用curl -X POST localhost:8090/one -H 'content-type: application/json;charset=UTF-8' -H 'name: test' -H 'postman-token: 8e87369d-e2e2-ab25-eadd-f40f0682e593' -d '{"name":"Roopesh", "no":"123123"}'

  1. 不发送demoEntity=。Body 应该只包含 json 本身。
  2. 使用-d密钥发送数据。-F适用于多部分主体。有点不同。


Kun*_*tre 5

如果您使用 Postman 客户端来测试您的 Rest API,则有可能您必须在选项卡"form-data"而不是"raw"下添加正文。