1、报错信息
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('s' (code 115)): was expecting double-quote to start field name
at [Source: (String)"{stu_id:"1001",stu_name:"晓春"}"; line: 1, column: 3]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:2391) ~[jackson-core-2.13.5.jar:2.13.5]
2、问题描述
生成的JSON字符串,属性没有使用双引号或者单引号,引发的解析错误问题
错误代码如下:stu_id和stu_name没有加入双引号
@RequestMapping("/commonQuestion9")
@ResponseBody
public void commonQuestion9() throws Exception{
ObjectMapper mapper = new ObjectMapper();
String param="{stu_id:\"1001\",stu_name:\"晓春\"}";
//将字符串转换为对象
Student stu=mapper.readValue(param,Student.class);
}
3、解决办法
在程序中使用如下配置:
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
正确代码演示:
@RequestMapping("/commonQuestion9")
@ResponseBody
public void commonQuestion9() throws Exception{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
String param="{stu_id:\"1001\",stu_name:\"晓春\"}";
//将字符串转换为对象
Student stu=mapper.readValue(param,Student.class);
}