gpt4 book ai didi

java - 如何修复从 LinkedTreeMap 到 ArrayList 的 Gson JSON 解析?

转载 作者:行者123 更新时间:2023-11-30 10:33:43 32 4
gpt4 key购买 nike

我正在使用 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

这是 Debug模式下的原始响应: enter image description here

最佳答案

您缺少 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
}

但我强烈建议您将 AutoValue 与 Gson 扩展一起使用,然后您的模型将如下所示:

@AutoValue
public abstract class GetGoogleMapPlacesResponse {
@SerializedName("predictions") public abstract List<GooglePlace> googlePlaces;
public abstract String status;
}

有关更多信息,请查看此处:https://github.com/rharter/auto-value-gson

关于java - 如何修复从 LinkedTreeMap 到 ArrayList 的 Gson JSON 解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42071692/

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