【问题标题】:Convert JSONP to JSON with Spring RestTemplate使用 Spring RestTemplate 将 JSONP 转换为 JSON
【发布时间】:2015-08-03 13:24:50
【问题描述】:

我有一项服务,它下载包含 JSON 的 JSONP 文件并对其进行处理。我正在尝试以正确的 Spring 方式进行操作,但我还没有找到任何针对这种特定场景的教程(尽管有很多关于将 json 转换为 jsonp 的内容)。

为了说明问题,假设我点击了以下网址:“https://www.example.com/file.jsonp”,其中包含以下内容:

callback(
 { 
   "field1": "value1", 
   "field2": "value2"
 }
);

为了处理 JSON,我需要删除回调(我目前正在使用子字符串手动执行此操作)。 Spring中是否有任何推荐的方式如何直接从这个JSONP文件中获取POJO?

假设我只有带注释的 pojo 并且只想调用:

  RestTemplate restTemplate = new RestTemplate();
  Pojo pojo = restTemplate.getForObject(url, Pojo.class);

目前,它给了我以下异常:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.berrycloud.blueberry.monitor.price.model.OnDemandPricePOJO] and content type [application/javascript]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
...

感谢您提供的任何提示。我希望这不是重复的。

【问题讨论】:

  • 你的类路径中有Jackson 1Jackson 2 吗?因为您需要默认 JSON HttpMessageConverter
  • 我的类路径中有 Jackson 2.4.4。

标签: java json spring rest


【解决方案1】:

事实证明,我的问题中描述的 JSONP 对象没有内置转换器。我最终手动删除了字符串的开头和结尾,然后将其余部分转换为标准 JSON。

另一种可能性是实现自定义MessageConvertor 并在那里预处理 JSONP 对象。

可以在HERE 找到有关如何编写自定义消息转换器的精彩教程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2013-08-19
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多