【问题标题】:Spring boot Unexpected character % code 37春季启动意外字符%代码37
【发布时间】:2020-08-05 15:12:33
【问题描述】:

我正在尝试读取包含 json 类型数据的字符串类型属性:

代码反应 js:

axios.post("http://localhost:8080/MenuFiltre/filtreregioncloser",JSON.stringify(FilterRegion))

代码弹簧启动:

@PostMapping("/filtreregioncloser")
    public Iterable<Closerfprfx>gettab1(@RequestBody String filterRegion) throws JsonMappingException, JsonProcessingException
    {
        
    ObjectMapper mapper = new ObjectMapper();
    FilterRegionOne fro = mapper.readValue(filterRegion, FilterRegionOne.class);
    

        
        System.out.println(fro.isRfx());

         return null;      
    }

但是当我尝试在控制台中显示数据时出现此错误

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('%' (code 37)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (String)"%7B%22rfx%22%3Atrue%2C%22rfp%22%3Atrue%2C%22rfp_x%22%3Atrue%2C%22allclassification%22%3Atrue%2C%22eu%22%3Afalse%2C%22americas%22%3Afalse%2C%22aae%22%3Afalse%2C%22ger%22%3Afalse%2C%22eu2%22%3Afalse%2C%22latam%22%3Afalse%2C%22empty%22%3Afalse%2C%22allregion%22%3Afalse%2C%22idm%22%3Afalse%2C%22dig%22%3Afalse%2C%22eps%22%3Afalse%2C%22allpractice%22%3Afalse%2C%22c

请问我现在应该做什么来显示数据!

【问题讨论】:

  • 出于某种原因,您正在对 JSON 进行 URL 编码。也许您需要设置一个 content-type 来防止 Axios 将其视为表单?
  • 在此处查看示例:github.com/axios/axios 没有一个示例使用JSON.stringify 作为第二个参数。所以可能你应该将数据作为对象传递,而不是字符串化。
  • filterRegion的输入是什么?

标签: java json reactjs spring-boot axios


【解决方案1】:

对于 axios,您的第二个参数需要是 JSON 对象本身,因此请删除 JSON.stringify()

axios.post("http://localhost:8080/MenuFiltre/filtreregioncloser", FilterRegion)

另外,在您的控制器中,我建议在 JSON 到达您的方法之前对其进行解析,以减少样板代码:

@PostMapping("/filtreregioncloser")
public Iterable<Closerfprfx>gettab1(@RequestBody FilterRegionOne filterRegion) {
    System.out.println(fro.isRfx());
    return null;
}

【讨论】:

    【解决方案2】:

    如果 FilterRegion 是 POST 请求的请求主体,那么您在使用 axios 时不需要对其进行 JSON 字符串化,axios 会为您处理。

    此外,如果您在类级别使用 @RestController 注释而不是 @Controller(看不到您使用了什么),那么 spring 将处理 JSON 映射,您可以立即访问 POJO

    @PostMapping("/filtreregioncloser")
        public Iterable<Closerfprfx>gettab1(@RequestBody FilterRegionOne filterRegion {
        
        }
    

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 2015-01-08
      • 1970-01-01
      • 2017-09-11
      • 2015-04-18
      • 2017-06-24
      • 2015-08-22
      • 2015-09-18
      • 2015-03-20
      相关资源
      最近更新 更多