简体   繁体   English

Spotify创建播放列表Java-响应代码400,“ JSON解析错误”

[英]Spotify Create Playlist Java - Response Code 400, “Error parsing JSON”

I am trying to create a playlist using the Spotify API, and I am writing the POST request to the Spotify API endpoint in Java. 我正在尝试使用Spotify API创建播放列表,并且正在将POST请求写入Java中的Spotify API端点。 I have also included every available scope from Spotify when I retrieve my access token. 检索访问令牌时,我还包括了Spotify中所有可用的范围。 This is returning a response with an error message of: 这将返回错误消息:

{"error":{"message":"Error parsing JSON.","status":400}} {“错误”:{“消息”:“解析JSON时出错。”,“状态”:400}}

Here is what I have: 这是我所拥有的:

String http = "https://api.spotify.com/v1/users/" + userId + "/playlists";

CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(http);

JsonObject entityObj = new JsonObject();
JsonObject dataObj = new JsonObject();
dataObj.addProperty("name", "title");
dataObj.addProperty("public", "false");
entityObj.add("data", dataObj);

String dataStringify = GSON.toJson(entityObj);
StringEntity entity = new StringEntity(dataStringify);
post.setEntity(entity);

post.setHeader("Authorization", "Bearer " + accessToken);
post.setHeader("Content-Type", "application/json");

CloseableHttpResponse response = client.execute(post);

System.out
    .println("Response Code : " + response.getStatusLine().getStatusCode());
String resp = EntityUtils.toString(response.getEntity());
JSONObject responseObj = new JSONObject(resp);
System.out.println(responseObj);

client.close();

Please let me know if you have any insights into what is wrong. 如果您对问题有任何见解,请告诉我。

I am assuming you are using the org.json library as well as Google's Gson library. 我假设您正在使用org.json库以及Google的Gson库。 Using both doesn't make sense in this context. 在这种情况下,两者都没有意义。 You won't need 你不需要

String dataStringify = GSON.toJson(entityObj);

as entity Object already is a JSON Object. 因为实体对象已经是JSON对象。 entityObj.toString() should be enough. entityObj.toString()应该足够了。 The current JSON Data you are sending looks like this: 您正在发送的当前JSON数据如下所示:

{
 "data":
   {
    "name":"title",
    "public":"false"
   }
}

Spotify ask for an JSON Object like this: Spotify要求这样的JSON对象:

{
  "name": "New Playlist",
  "public": false
}

You only have to send the Data Object dataObj. 您只需要发送数据对象dataObj。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM