エラーが発生しています。
次の理由により、JSONの解析に失敗しました:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:BEGIN_ARRAYが必要ですが、1行2列目がBEGIN_OBJECTでした
サーバーのURL
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() {
}
}
どうすればこれを解決できますか?
あなたは返されたJSONがこれであることをコメントで述べています:
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Post
オブジェクトの配列があることをGsonに伝えています。
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));
あなたはしません。JSONは正確に1つのPost
オブジェクトを表し、Gsonがそれを伝えています。
コードを次のように変更します。
Post post = gson.fromJson(reader, Post.class);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加