使用SpringMVC和Jackson将JSON输入映射到java.util.Map
目标:使用反射API对补丁请求进行一般性实现 上下文:之前有一个POST请求(JSON输入:完整对象,所有字段)。现在我想用补丁请求(JSON输入:部分对象,仅更新字段)替换它。因此,我需要用类似于使用SpringMVC和Jackson将JSON输入映射到java.util.Map,java,rest,spring-mvc,annotations,jackson,Java,Rest,Spring Mvc,Annotations,Jackson,目标:使用反射API对补丁请求进行一般性实现 上下文:之前有一个POST请求(JSON输入:完整对象,所有字段)。现在我想用补丁请求(JSON输入:部分对象,仅更新字段)替换它。因此,我需要用类似于@RequestBody-Map-entityFieldValues的内容替换@RequestBody-Entity-Entity JSON输入: { "active": false } 我试过什么: @RequestMapping( value = "/{entityId}", metho
@RequestBody-Map-entityFieldValues
的内容替换@RequestBody-Entity-Entity
JSON输入:
{
"active": false
}
我试过什么:
@RequestMapping( value = "/{entityId}", method = RequestMethod.PATCH )
public void patch( @PathVariable( "entityId" ) final Long entityId, @RequestBody Map<String, Object> fieldValues) {
// load entity from DB and update values using reflection (BeanUtils)
service.patch( entityId, fieldValues);
}
@RequestMapping(value=“/{entityId}”,method=RequestMethod.PATCH)
公共无效修补程序(@PathVariable(“entityId”)最终长entityId,@RequestBody映射字段值){
//从DB加载实体并使用反射(BeanUtils)更新值
补丁(entityId,FieldValue);
}
它不起作用了。当我使用POSTMAN测试此控制器时,我面临HTTP错误501未实现。目前,我正在使用以下解决方法:
@RequestMapping( value = "/{entityId}", method = RequestMethod.PATCH )
public void tooglePublished( @PathVariable( "entityId" ) final Long entityId, @RequestBody String body) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
// TODO : make it work using something like: @RequestBody Map<String, String> fieldValues
Map<String, Object> fieldValues = mapper.readValue(body,new TypeReference<Map<String, Object>>() {});
// load entity from DB and update values using reflection (BeanUtils)
service.patch( entityId, fieldValues);
}
@RequestMapping(value=“/{entityId}”,method=RequestMethod.PATCH)
public void tooglePublished(@PathVariable(“entityId”)最终长entityId,@RequestBody String body)抛出JsonParseException、JsonMappingException、IOException{
ObjectMapper mapper=新的ObjectMapper();
//TODO:使用类似于:@RequestBody映射fieldValues的内容使其工作
Map fieldValues=mapper.readValue(body,new-TypeReference(){});
//从DB加载实体并使用反射(BeanUtils)更新值
补丁(entityId,FieldValue);
}
有人知道我如何使用SpringMVC注释使它工作吗
弹簧4.1.1.释放
杰克逊1.9.13
谢谢这没有意义<代码>501未实现意味着web服务器根本不支持该方法(
补丁
),因此第二个示例也会失败。也许你在《邮递员》中选错了方法
为了使用@RequestBody映射
,您还必须发送正确的内容类型
标题