我知道我来晚了,但我一直在寻找解决方案,但没有找到任何东西。经过大量努力,我发现发送带有“@BODY”的杰克逊“对象”没有帮助,当我将类型更改为“字符串”时,它对我有用。
这是我的代码
def save(@Body String JSON){
def result = [:]
ObjectMapper objectMapper = new ObjectMapper();
//convert json string to object
def obj = objectMapper.readValue(JSON, Course.class);
println(obj)
Course course = new Course(name: obj?.name, pre: obj?.pre,
regno: obj?.regno, enrolled: obj?.enrolled)
course.validate()
if(course.hasErrors()){
println("Error: "+course.errors)
result.put("Error is: ",course.errors)
return result;
}
course.save(flush:true,failOnError: true)
result.put("Message","Successfully Created")
result.put("Result",course)
return HttpResponse.created(result)
}
将它传递给 ObjectMapper,然后将它从 JSON 字符串转换为 Java 对象对我有用。
我传递的Json字符串如下:
{
"name" : "Data Structures",
"pre" : "Computer Programming",
"regno" : "249",
"enrolled" : "90"
}
这是数据库更改前后数据的存储:
+----+---------+------------------------+-------------------------------+----+
| id | version | name | pre | regno |enrolled |
+----+---------+------------------------+-------------------------------+----+
| 1 | 0 | "Computer Programming" | "Introduction to Programming"| "233"|"26"|
| 2 | 0 | Data Structures | Computer Programming | 249 | 90 |
+----+---------+------------------------+-------------------------------+----+
希望答案可以帮助任何正在寻找上述解决方案的替代解决方案的人。