gpt4 book ai didi

java - 应为 BEGIN_ARRAY 但在第 1 行第 2 列为 BEGIN_OBJECT

转载 作者:太空狗 更新时间:2023-10-29 22:31:34 25 4
gpt4 key购买 nike

我遇到错误。

Failed to parse JSON due to: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

服务器地址

public static final String SERVER_URL = "https://maps.googleapis.com/maps/api/timezone/json?location=-37.8136,144.9631&timestamp=1389162695&sensor=false";

执行请求

    try {
// Create an HTTP client
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(SERVER_URL);

// Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();

try {
// Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));

content.close();

for (Post p : postsList) {
System.out.println(p.timeZoneId);
}

} catch (Exception ex) {
System.out.println("Failed to parse JSON due to: " + ex);
}
} else {
System.out.println("Server responded with status code: "
+ statusLine.getStatusCode());
}
} catch (Exception ex) {
System.out
.println("Failed to send HTTP POST request due to: " + ex);
}

课后

public class Post {
public String timeZoneId;
public Post() {

}
}

我该如何解决这个问题?

最佳答案

您在评论中声明返回的 JSON 是这样的:

{ 
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}

你告诉 Gson 你有一个 Post 对象数组:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));

你不知道。 JSON 只代表一个 Post 对象,Gson 会告诉您这一点。

将您的代码更改为:

Post post = gson.fromJson(reader, Post.class);

关于java - 应为 BEGIN_ARRAY 但在第 1 行第 2 列为 BEGIN_OBJECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20991386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com