天道酬勤,学无止境

Spring RestTemplate with Jackson throws “Can not resolve BeanPropertyFilter” when using @JsonFilter

Can I specify the Jackson ObjectMapper that Spring's RestTemplate uses?

I'm not 100% that's what I need to do but see below for details.

Background: With help from this StackOverflow post I added @JsonFilter to my domain class and edited my jax-rs web service (implemented in CXF). I'm now successfully able to dynamically select which domain class fields to return in my RESTful API. So far so good.

I'm using Spring's RestTemplate in my JUnit tests to test my RESTful API. This was working fine until I added @JasonFilter to my domain class. Now I'm getting the following exception:

org.springframework.web.client.ResourceAccessException: I/O error: Can not resolve BeanPropertyFilter with id 'apiFilter'; no FilterProvider configured; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not resolve BeanPropertyFilter with id 'apiFilter'; no FilterProvider configured

at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:453)

rest of stack trace omitted for brevity

Caused by: org.codehaus.jackson.map.JsonMappingException: Can not resolve BeanPropertyFilter with id 'apiFilter'; no FilterProvider configured

at org.codehaus.jackson.map.ser.BeanSerializer.findFilter(BeanSerializer.java:252)

I was getting a similar problem on the server side and was able to resolve it (with help from this post) by giving a FilterProvider to the Jackson ObjectMapper as follows:

ObjectMapper mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider().addFilter("apiFilter", SimpleBeanPropertyFilter.filterOutAllExcept(filterProperties));

Can I do something similar on the RestTemplate side? Any ideas of how to solve this issue are appreciated.

Just to be clear, on the client RestTemplate side I do not want to filter the domain object properties at all.

标签

评论

Can I specify the Jackson ObjectMapper that Spring's RestTemplate uses?

I was able to force RestTemplate to use a customized ObjectMapper by doing the following:

ObjectMapper mapper = new ObjectMapper();

// set a custom filter
Set<String> filterProperties = new HashSet<String>();
FilterProvider filters = new SimpleFilterProvider().addFilter("apiFilter", SimpleBeanPropertyFilter.serializeAllExcept(filterProperties));
mapper.setFilters(filters);

MappingJacksonHttpMessageConverter messageConverter = new MappingJacksonHttpMessageConverter();
messageConverter.setObjectMapper(mapper);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(messageConverter);
restTemplate.setMessageConverters(messageConverters);

This website provided example for part of the above code.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Spring Resttemplate postforobject returns null as object response if used with ClientHttpRequestInterceptor
    I am trying to consume a rest service and i am posting some data, with Spring RestTemplate postForObjectMethod but i am getting a null response, even though i can see the request and response in payload. [Update] I am using an interceptor implmenting ClientHttpRequestInterceptor, if i remove it, i am getting the response. [PS: the service is configured as POST, ideally it should be GET for obvious reason, but i am still curious why no response is coming as part of post, even i can see the same in http logs.] Configuration Spring MVC 4 based application Application context: <bean id=
  • 找不到适合响应类型的HttpMessageConverter(no suitable HttpMessageConverter found for response type)
    问题 使用spring,使用以下代码: List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters(); for(HttpMessageConverter httpMessageConverter : messageConverters){ System.out.println(httpMessageConverter); } ResponseEntity<ProductList> productList = restTemplate.getForEntity(productDataUrl,ProductList.class); 我懂了 org.springframework.http.converter.ByteArrayHttpMessageConverter@34649ee4 org.springframework.http.converter.StringHttpMessageConverter@39fba59b org.springframework.http.converter.ResourceHttpMessageConverter@383580da org.springframework.http.converter.xml
  • Spring 4.2.3和fasterxml Jackson 2.7.0不兼容(Spring 4.2.3 and fasterxml Jackson 2.7.0 are incompatible)
    问题 从fasterxml.jackson 2.6.3迁移到2.7.0之后。 这是因为删除了Spring的AbstractJackson2HttpMessageConverter使用的public JavaType constructType(Type type, Class<?> contextType)方法。 如何解决这个问题? 我正在使用Spring 4.2.3。 /signin/facebook java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.type.TypeFactory.constructType(Ljava/lang/reflect/Type;Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/JavaType; at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.getJavaType(AbstractJackson2HttpMessageConverter.java:314) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter
  • 使用RestTemplate获取InputStream(Getting InputStream with RestTemplate)
    问题 我正在使用URL类从中读取InputStream。 有什么我可以使用RestTemplate的方法吗? InputStream input = new URL(url).openStream(); JsonReader reader = new JsonReader(new InputStreamReader(input, StandardCharsets.UTF_8.displayName())); 如何使用RestTemplate而不是URL获得InputStream ? 回答1 您不应该直接获取InputStream 。 RestTemplate旨在封装处理响应(和请求)内容。 它的优势在于处理所有IO,并为您提供现成的Java对象。 RestTemplate的原始作者之一Brian Clozel表示: RestTemplate并非意在流式传输响应主体; 它的合同不允许这样做,而且已经存在了很长时间,以至于在不中断许多应用程序的情况下就无法更改其行为的这一基本部分。 您需要注册适当的HttpMessageConverter对象。 这些将可以通过HttpInputMessage对象访问响应的InputStream 。 正如Abdull所建议的那样,Spring确实为Resource提供了HttpMessageConverter实现,该实现本身包装了InputStream
  • Problem returning stream of responses from gRPC service to RESTful client
    I am attempting to write a set of services that will provide a REST interface to external clients, while using gRPC/protobuf for inter-service communication internally. Spring Boot is being utilized to help with the background infrastructure support. I only started learning and working with Google protobuf and gRPC about a week ago. I have been able to successfully get simpler processing to work from end-to-end, but these are returning a single object (i.e. no streaming). I'm having a problem with a call that is intended to stream a collection of response objects. The other thing to note is
  • Spring RestTemplate使用Jackson作为HttpMessageConverter和joda DateTime属性进行反序列化(Spring RestTemplate with Jackson as HttpMessageConverter and joda DateTime property fails to deserialize)
    问题 情况如下。 我有一个ObjectMapper(Jackson 2),它注册一个JodaModule,能够序列化和反序列化Joda DateTime类型。 此ObjectMapper已使用自定义JSON字符串进行了测试,并且可以正常工作。 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JodaModule()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); objectMapper.setDateFormat(new ISO8601DateFormat()); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper; 我有一个RestTemplateFactory
  • 具有分页API的Spring RestTemplate(Spring RestTemplate with paginated API)
    问题 我们的REST API在Pages中返回结果。 这是一个控制器的示例 @RequestMapping(value = "/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8") @ResponseStatus(HttpStatus.OK) public Page<MyObject> findAll(Pageable pageable) { ... } 有没有一种简单的方法可以通过RestTemplate使用该API? 如果我们这样做 ParameterizedTypeReference<Page<MyObject>> responseType = new ParameterizedTypeReference<Page<MyObject>>() { }; ResponseEntity<Page<MyObject>> result = restTemplate.exchange(url, HttpMethod.GET, null/*httpEntity*/, responseType); List<MyObject> searchResult = result.getBody().getContent(); 引发异常 org
  • 如何使用杰克逊使用本地化的十进制分隔符反序列化浮点值(How to deserialize a float value with a localized decimal separator with Jackson)
    问题 我正在用Jackson解析的输入流包含纬度和经度值,例如: { "name": "product 23", "latitude": "52,48264", "longitude": "13,31822" } 由于某种原因,服务器使用逗号作为小数点分隔符,从而产生InvalidFormatException 。 由于我无法更改服务器输出格式,因此我想教Jackson的ObjectMapper处理这些情况。 以下是相关代码: public static Object getProducts(final String inputStream) { ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.readValue(inputStream, new TypeReference<Product>() {} ); } catch (UnrecognizedPropertyException e) { e.printStackTrace(); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch
  • 当HTTP请求的返回状态为401时,如何解析Java中的响应正文(How to parse the response body in Java, when the HTTP request has return status 401)
    问题 我正在使用Spring的RestTemplate和Jackson来使用RESTful JSON API。 在某些情况下,我们可能会收到带有自定义JSON主体的Status 401 (未经授权)响应,该响应由API制造商定义,如下所示: { "code": 123, "message": "Reason for the error" } 我们需要解析主体,并在业务逻辑中使用code属性。 这是我们需要解析为的错误响应Java对象: public class CustomError { @JsonProperty private Integer code; @JsonProperty private String message; public Integer getCode() { return code; } public String getMessage() { return message; } } 还有一个自定义错误处理程序可以做到这一点: public class CustomErrorHandler extends DefaultResponseErrorHandler { private RestTemplate restTemplate; private ObjectMapper objectMapper; private
  • Spring RestTemplate with Jackson as HttpMessageConverter and joda DateTime property fails to deserialize
    The scenario is as follows. I have an ObjectMapper (Jackson 2) that registers a JodaModule, capable of serializing and de-serializing Joda DateTime type. This ObjectMapper is tested with custom JSON strings and works as expected. ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JodaModule()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); objectMapper.setDateFormat(new ISO8601DateFormat()); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.configure
  • 无法提取响应:找不到合适的HttpMessageConverter作为响应类型(Could not extract response: no suitable HttpMessageConverter found for response type)
    问题 我是spring集成的新手,并且可以根据我的项目需求使用spring集成http模块。 我正在从出站网关作为HTTP客户端发送请求。 我正在尝试向服务器发起请求,并且服务器应使用我的设置值向我返回消息有效负载。 我正在将对象转换为JSON,用于发送到服务器。我正在从以下所示的client(HttpClientDemo)向服务器端存在的入站网关发送请求。 为此,我将对象转换为JSON,然后在客户端将对象转换为JSON字符串,然后在客户端执行一些简单操作,然后将其发送回客户端(HttpClientDemo),但在此之前,我遇到了与HttpMessageConverter如下: Exception in thread "main" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.mycompany.MyChannel.model.FFSampleResponseHttp] and content type [text/plain;charset=UTF-8] at org.springframework.web.client
  • Spring RestTemplate给出“ 500”错误,但URL相同,credentails在RestClient和Curl中起作用(Spring RestTemplate gives “500” error but same URL, credentails works in RestClient and Curl)
    问题 一个网址,凭据可在RestClient用户界面以及Curl中使用,当通过Spring RestTemplate访问相同内容时,我得到“ 500”错误。 我正在使用以下代码: MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); map.add("name", user); map.add("password", password); restTemplate.postForObject(url, request, Employee.class, map); 请让我知道您的建议或意见,以解决该问题。 回答1 我建议创建您的HttpComponentsClientHttpRequestFactory并将其传递给RestTemplate ,如下所述: ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(HttpClients.createDefault()); RestTemplate restTemplate = new RestTemplate(requestFactory); 通过这种方式,您可以在测试应用程序时避免服务器端问题(例如面临错误代码500)。
  • Could not extract response: no suitable HttpMessageConverter found for response type
    I am new with spring integration and working in spring integration http module for my project requirement. I am sending request from outbound gateway as a http client. I am trying to initiate a request to the server and server should return me the message payload with my set values. I am converting object to JSON using to send to server I am sending a request to inbound gateway present on the server side from client(HttpClientDemo) shown below. For that purpose, I am converting my object into the JSON and then converting to JSON string to object on the client side, performing some simple
  • 无法在Spring 3 REST Web服务中从START_ARRAY令牌中反序列化对象的实例(Cannot deserialize instance of object out of START_ARRAY token in Spring 3 REST Webservice)
    问题 我正在利用Spring提供的这个很酷的功能:Spring RESTWebService(spring的版本为3)。 如果我从浏览器访问URL,则可以看到JSON响应,但是可以从客户端端点(Android应用程序)看到以下错误消息: Caused by: org.springframework.web.client.ResourceAccessException: I/O error: Can not deserialize instance of MyObject out of START_ARRAY token at [Source: org.apache.http.conn.EofSensorInputStream@4076e940; line: 1, column: 1]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of MyObject out of START_ARRAY token at [Source: org.apache.http.conn.EofSensorInputStream@4076e940; line: 1, column: 1] at org.springframework.web.client
  • SpringMVC+RestFul详细示例实战教程(实现跨域访问)
    一、理解 REST REST(Representational State Transfer),中文翻译叫“表述性状态转移”。是 Roy Thomas Fielding 在他2000年的博士论文中提出的。它与传统的 SOAP Web 服务区别在于,REST关注的是要处理的数据,而 SOAP 主要关注行为和处理。要理解好 REST,根据其首字母拆分出的英文更容易理解。 表述性(Representational):对于 REST 来说,我们网络上的一个个URI资源可以用各种形式来表述,例如:XML、JSON或者HTML等。 状态(State): REST 更关注资源的状态而不是对资源采取的行为。 转移(Transfer):在网络传输过程中,REST 使资源以某种表述性形式从一个应用转移到另一个应用(如从服务端转移到客户端)。 具体来说,REST 中存在行为,它的行为是通过 HTTP 表示操作的方法来定义的即:GET、POST、PUT、DELETE、PATCH;GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源,PATCH用来更新资源。 基于 REST 这样的观点,我们需要避免使用 REST服务、REST Web服务 这样的称呼,这些称呼多少都带有一些强调行为的味道。 二、使用 RESTful 架构设计使用误区 RESTful
  • Cannot deserialize instance of object out of START_ARRAY token in Spring 3 REST Webservice
    I am making use of this cool thing Spring offers: Spring RESTWebService (Version of spring is 3). If I access the URL from browser I can see the JSON response, but from a Client endpoint (Android application) iIreceive this error message: Caused by: org.springframework.web.client.ResourceAccessException: I/O error: Can not deserialize instance of MyObject out of START_ARRAY token at [Source: org.apache.http.conn.EofSensorInputStream@4076e940; line: 1, column: 1]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of MyObject out of START_ARRAY token
  • 如何使用RestTemplate Spring-mvc发送Multipart表单数据(How to send Multipart form data with restTemplate Spring-mvc)
    问题 我正在尝试使用Jetty将带有RestTemplate的文件上传到Raspberry Pi。 在Pi上,正在运行一个servlet: protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter outp = resp.getWriter(); StringBuffer buff = new StringBuffer(); File file1 = (File) req.getAttribute("userfile1"); String p = req.getParameter("path"); boolean success = false; if (file1 == null || !file1.exists()) { buff.append("File does not exist\n"); } else if (file1.isDirectory()) { buff.append("File is a directory\n"); } else { File outputFile = new File(req.getParameter("userfile1")); if
  • Spring 4.2.3 and fasterxml Jackson 2.7.0 are incompatible
    After migration from fasterxml.jackson 2.6.3 to 2.7.0. This is because public JavaType constructType(Type type, Class<?> contextType) method used in Spring's AbstractJackson2HttpMessageConverter was removed. How to fix this? I am using Spring 4.2.3. /signin/facebook java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.type.TypeFactory.constructType(Ljava/lang/reflect/Type;Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/JavaType; at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.getJavaType(AbstractJackson2HttpMessageConverter.java:314) at org
  • Generics with Spring RESTTemplate
    I have a class like that: public class Wrapper<T> { private String message; private T data; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } } and I use resttemplate as follows: ... Wrapper<Model> response = restTemplate.getForObject(URL, Wrapper.class, myMap); Model model = response.getData(); ... However it throws a: ClassCastException I read that: Issue when trying to use Jackson in java but didn't help. There are some topics related to my
  • How to call HTTPS restful web services using Spring RestTemplate
    I am using Tomcat7, Spring framework for ReST web services. I am trying to call an https web service using Spring RestTemplate. I am getting the following error: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target I check online at stackoverflow. I tried the sample code from the url: Access Https Rest Service using Spring RestTemplate I