我有以下JSON對象,我想使用Google的GSON庫反序列化它。不幸的是,我無法正確地獲取列表。 GSON找到第一個列表條目,但不是第二個。使用GSON反序列化列表
這是我用來調用代碼GSON:
Mentions result = gson.fromJson(response, Mentions.class);
這裏是我的JSON文件:
{
"mentions": [
{
"allEntities": [
{
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
],
"name": "Dylan",
"bestEntity": {
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
},
{
"name": "Duluth",
"bestEntity": {
"kbIdentifier": "YAGO:Duluth\\u002c_Minnesota",
"disambiguationScore": "0.63149"
}
}
]
}
這些都是我所創建的普通Java對象:
public class Mentions {
public List<Mention> mentions = new ArrayList<>();
}
public class Mention {
@SerializedName("bestEntity")
public BestEntity entity;
@SerializedName("name")
public String name;
}
public class BestEntity {
@SerializedName("kbIdentifier")
public String kbIdentifier;
@SerializedName("disambiguationScore")
public Double disambiguationScore;
}
我也嘗試直接反序列化列表,但它只是給了我一個錯誤,說GSON希望列表啓動一個t輸入的開始。
Type datasetListType = new TypeToken<Collection<Mention>>() {
}.getType();
List<Mention> mentions = gson.fromJson(response, datasetListType);
你可以發佈你與你想要的結果,結果呢? – Tunaki
難道你不會錯過'allEntities'的一些映射嗎? –
所有實體均不包含相關信息。真正的JSON文件包含更多不相關的信息,我只是忘記從最小的例子中刪除AllEntities。 當然,如果我稍後決定需要AllEntities,我會添加一個映射。 – icehawk