[alibaba/fastjson]FastJsonHttpMessageConverter一定会执行JSON.parseObject

2025-11-03 329 views
2
private Object readType(Type type, HttpInputMessage inputMessage) throws IOException {

        try {
            InputStream in = inputMessage.getBody();
            return JSON.parseObject(in, fastJsonConfig.getCharset(), type, fastJsonConfig.getFeatures());
        } catch (JSONException ex) {
            throw new HttpMessageNotReadableException("JSON parse error: " + ex.getMessage(), ex);
        } catch (IOException ex) {
            throw new HttpMessageNotReadableException("I/O error while reading input message", ex);
        }
    }

是否判断type不是基本类型才parseObject更符合逻辑, 我现在遇到的情况是配置了FastJsonHttpMessageConverter, 未指定produces的post rest api提交不是json格式的body时会出错

回答

8

@zhangfei9734 能否提供一下testcase 说明一下你的问题

5
@RequestMapping(path = '/test', method = [RequestMethod.POST] )
Map<String, Object> test(@RequestBody String body){
    // ...
}

// test 
def body = """
---
domain: name
"""
 RestAssured.given().contentType(ContentType.URLENC).body(body).post('/test')

这样就会报错,我没有指定path的请求头为json,而我实际提交的只是一个String的类型,但是FastJsonHttpMessageConverter没有判断test解释的实际类型是什么都进行了parseObjet所以出错了。 @VictorZeng

3

@zhangfei9734 问题在于你的 Content-Type 是 application/x-www-form-urlencoded http请求报文类型如果是application/x-www-form-urlencoded 你提交的数据会格式就会是这样子 根本无法解析

Parameters = {{"domain":"name"}=[null]}
Headers = {Content-Type=[application/x-www-form-urlencoded]}
4

@zhangfei9734 如果提交是JSON格式的数据 Content-Type 使用 application/json 而使用 application/x-www-form-urlencoded 时一般是使用form表单提交 通过@RequestParam 绑定参数 而不是@RequestBody

7

urlencoded时应该使用query string方式提交parameters