RestTemplate中的访问元素

问题描述 投票:0回答:2

我最近开始学习Java和Spring引导,并希望使用Spotify api来获取有关艺术家的信息。

我已经使用了以下内容,并且得到了回复


String accessToken = getToken(); // method made to generate token
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> retrieveArtistInfo = restTemplate.exchange("https://api.spotify.com/v1/artists"+"?ids="+Arrays.toString(ids).replace("[", "").replace("]", ""), HttpMethod.GET, request, Object.class);



Response: 

{
"artists": [
{
"headers": {
"Content-Type": [
"application/json; charset=utf-8"
],
"Cache-Control": [
"public, max-age=72437"
],
"X-Robots-Tag": [
"noindex, nofollow"
],
"Access-Control-Allow-Origin": [
"*"
],
"Access-Control-Allow-Headers": [
"Accept, App-Platform, Authorization, Content-Type, Origin, Retry-After, Spotify-App-Version, X-Cloud-Trace-Context"
],
"Access-Control-Allow-Methods": [
"GET, POST, OPTIONS, PUT, DELETE, PATCH"
],
"Access-Control-Allow-Credentials": [
"true"
],
"Access-Control-Max-Age": [
"604800"
],
"content-length": [
"916"
],
"Date": [
"Mon, 13 Apr 2020 07:42:09 GMT"
],
"Via": [
"1.1 google"
],
"Alt-Svc": [
"clear"
]
},
"body": {
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/4q3ewBCX7sLwd24euuV69X"
},
"followers": {
"href": null,
"total": 20399255
},
"genres": [
"latin",
"reggaeton",
"trap latino"
],
"href": "https://api.spotify.com/v1/artists/4q3ewBCX7sLwd24euuV69X",
"id": "4q3ewBCX7sLwd24euuV69X",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/23009960c33ef08d5973440cca17985a6c70a515",
"width": 640
},
{
"height": 320,
"url": "https://i.scdn.co/image/8ff3e392402169f239bce72b3d80c701b75150b8",
"width": 320
},
{
"height": 160,
"url": "https://i.scdn.co/image/624dd15f5bdcc1bae5fa47739601f3e0be62ebda",
"width": 160
}
],
"name": "Bad Bunny",
"popularity": 100,
"type": "artist",
"uri": "spotify:artist:4q3ewBCX7sLwd24euuV69X"
}
]
},
"statusCode": "OK",
"statusCodeValue": 200
}
]
}

我可以通过传递retrieveArtistInfo.getBody()来看到响应主体,但是我想从我存储它的对象中获取流派,外部URL之类的东西,然后做出自己的响应,但是我不知道该怎么做访问这些元素。有人会提供一些有关如何获得该提示的提示吗?

java spring-boot httpresponse spotify resttemplate
2个回答
0
投票

您正在此处查看的数据格式称为JSON。要访问该数据,您需要对其进行解析。 Spring世界中有很多工具可以解析该数据格式并与之交互。下面的一些链接

JSON简介:

在春季世界中,有很多工具可以自动将数据转换为可以使用的对象。或者,您可以将其解析为地图。一些示例(还有其他示例):


0
投票

这可以通过解析Joe对象前面提到的json对象来完成,通过使用com.google.gson

来完成
   ResponseEntity<String> response= restTemplate.getForEntity($url,String.class);//get First get response as string 
   JsonParser jsonParser = new JsonParser();                 
   JsonObject jo = (JsonObject)jsonParser.parse(response.getBody()); Convert it To POJO, which is mapped with JSON properties that returned as body from response which you sent request

然后通过对象的getter方法(以“ get”为前缀的函数。)访问属性。 例如:

    jo.getAsJsonObject("response").getAsJsonArray("artists")
© www.soinside.com 2019 - 2024. All rights reserved.