【问题标题】:Issues when trying to consume Spring REST尝试使用 Spring REST 时的问题
【发布时间】:2014-09-27 08:40:27
【问题描述】:

我有一个 REST 服务已经在运行,它返回下面的示例 JSON:

{
   "_embedded" : {
     "artist" : [ {
       "name" : "+44",
       "genre" : "Rock",
       "country" : "USA",
       "id" : 469,
       "_links" : {
         "self" : {
           "href" : <ADDRESS>
         },
         "albumList" : {
           "href" : <ADDRESS>
         }
       }
     } ]
   }
}

我正在尝试使用 RestTemplate 使用此资源,如下例所示

public static void main(String args[]) {
    RestTemplate restTemplate = new RestTemplate();
    Artist[] artistList = restTemplate.getForObject("http://localhost:8080/artists/search/findByName?name=+44", Artist[].class);
    for (Artist a : artistList)
        System.out.println(a.toString());
    }
}

当调试器点击 getForObject 行时,它得到这个错误:

Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException:
Could not read JSON: Can not deserialize instance of br.com.lagranzotto.itunes.frontend.entity.Artist[] out of START_OBJECT token

我已经在互联网上广泛搜索了大约一个星期,但没有成功找到此异常的原因。

【问题讨论】:

    标签: java spring rest jackson


    【解决方案1】:

    看起来您在 Web 服务中使用 Spring Data PagedResources,因此返回的 Artist 数据列表封装在 JSON 中的 _embedded 属性中。所以 RestTemplate 不知道如何反序列化它。

    查看 Why does RestTemplate not bind response representation to PagedResources? 并查看 Oliver Gierke 的回复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 2021-03-07
      相关资源
      最近更新 更多