我正在使用Retrofit + Gson解析JSON。
当我尝试从Google Places API解析响应时(好吧,我不尝试解析,我只是尝试为此响应制作模型)并且我收到了一些错误。
这是来自Google Place API的回复:
{
"predictions" : [
{
"description" : "Николаевская область, Украина",
"id" : "3bd747cc4efc2288da48942b909ce18a053c2060",
"matched_substrings" : [
{
"length" : 5,
"offset" : 0
}
],
"place_id" : "ChIJydRVsbqaxUARLq1R8Q3RgpM",
"reference" : "ClRPAAAAwseWiG8NUMt7TqSqz9rMP8R2M4rX7-cMRmIp4OCYL-VdRSr5B5T_PMwWzYOydVStVpYDvm0ldXYPEzxFAuvn1LqhtWHdROhsERwvmx0tVlwSEFdMw0sOe3rDaB2AqKKmF-YaFLvhiEOz3Bklv5-iTa7QQORILVCU",
"structured_formatting" : {
"main_text" : "Николаевская область",
"main_text_matched_substrings" : [
{
"length" : 5,
"offset" : 0
}
],
"secondary_text" : "Украина"
},
"terms" : [
{
"offset" : 0,
"value" : "Николаевская область"
},
{
"offset" : 22,
"value" : "Украина"
}
],
"types" : [ "administrative_area_level_1", "political", "geocode" ]
}, ...],
"status" : "OK"
}
这是我对此回复的模型:
public class GetGoogleMapPlacesResponse {
@SerializedName("predictions")
private List<GooglePlace> googlePlaces;
public List<GooglePlace> getGooglePlaces() {
return googlePlaces;
}
public void setGooglePlaces(List<GooglePlace> googlePlaces) {
this.googlePlaces = googlePlaces;
}
}
但是当Retrofit尝试解析对模型的响应时,我得到错误:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.myapp.net.rest.response.GetGoogleMapPlacesResponse
答案 0 :(得分:1)
您错过了GetGoogleMapPlacesResponse模型的构造函数。
public class GetGoogleMapPlacesResponse {
private List<GooglePlace> googlePlaces;
private String status;
public GetGoogleMapPlacesResponse(List<GooglePlace> googlePlaces, String status) {
this.googlePlaces = googlePlaces;
this.status = status;
}
...getters & setters
}
但我强烈建议您使用带有Gson扩展名的AutoValue,然后您的模型将如下所示:
@AutoValue
public abstract class GetGoogleMapPlacesResponse {
@SerializedName("predictions") public abstract List<GooglePlace> googlePlaces;
public abstract String status;
}
有关详情,请点击此处:https://github.com/rharter/auto-value-gson