预期BEGIN_ARRAY,但在第 1 行第 2 列BEGIN_OBJECT

2022-09-01 00:03:49

我得到以下错误。

由于以下原因,无法解析 JSON:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY 但在第 1 行第 2 列BEGIN_OBJECT

服务器网址

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() {

    }
}

我该如何解决这个问题?


答案 1

您在注释中声明返回的 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只代表一个对象,Gson正在告诉你这一点。Post

将您的代码更改为:

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

答案 2

您得到的响应是对象形式,即

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

替换以下代码行:

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

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