Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2(预期为 BEGIN_ARRAY,但在第 1 行第 2 列是 BEGIN_OBJECT)
问题描述
我遇到了错误.
解析 JSON 失败,原因是:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为 BEGIN_ARRAY,但为BEGIN_OBJECT 在第 1 行第 2 列
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×tamp=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() {
}
}
我该如何解决这个问题?
How could I solve this ?
推荐答案
你在评论中声明返回的 JSON 是这样的:
You state in the comments that the returned JSON is this:
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
你告诉 Gson 你有一个 Post
对象数组:
You're telling Gson that you have an array of Post
objects:
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));
你没有.JSON 恰好代表一个 Post
对象,而 Gson 正在告诉您这一点.
You don't. The JSON represents exactly one Post
object, and Gson is telling you that.
将您的代码更改为:
Post post = gson.fromJson(reader, Post.class);
这篇关于预期为 BEGIN_ARRAY,但在第 1 行第 2 列是 BEGIN_OBJECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:预期为 BEGIN_ARRAY,但在第 1 行第 2 列是 BEGIN_OBJECT
基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01