[英]Gson: deserializing arrays where elements are not of same type
我嘗試使用Gson庫反序列化json字符串; 我有以下課程
class Foo {
int Id;
String Name;
}
和以下json字符串
{response: [123, { id: 1, name: 'qwerty'}, { id: 2, name: 'asdfgh'}, ]}
我嘗試將此字符串反序列化
Gson gson = new Gson();
Foo[] res = gson.fromJson(jsonStr, Foo[].class);
但我失敗了,因為此字符串不包含純json數組,而是包含包含字段“ response”的對象(即數組)。 我的第二個麻煩是響應中除了Foo對象之外還包含文字“ 123”。
我想知道如何避免這些問題? 我是否應該手動解析字符串,提取數組的內容,從中刪除不必要的文字並將解析結果提供給fromJson方法,或者有什么方法可以幫助我使其更簡單?
沒有與您要反序列化的json數組兼容的Java類型。 您應該使用JsonParser獲取JsonObject,然后手動處理該JsonObject。
JsonParser p = new JsonParser();
JsonObject jsonObject = (JsonObject)p.parse(yourJsonString);
然后,您可以像這樣處理jsonObject:
List<Foo> foos = new ArrayList<Foo>();
JsonArray response = jsonObject.getAsJsonArray("response");
for (int i = 0; i < response.size(); i++) {
JsonElement el = response.get(i);
if (el.isJsonObject()) {
Foo f = new Foo();
JsonObject o = el.getAsJsonObject();
int id = o.getAsJsonPrimitive("id").getAsInt();
String name = o.getAsJsonPrimitive("name").getAsString();
f.Id = id;
f.Name = name;
foos.add(f);
}
}
或者,您可以這樣處理響應JsonArray:
List<Foo> foos = new ArrayList<Foo>();
JsonArray response = jsonObject.getAsJsonArray("response");
for (int i = 0; i < response.size(); i++) {
JsonElement el = response.get(i);
if (el.isJsonObject()) {
JsonObject o = el.getAsJsonObject();
Foo f = gson.fromJson(o, Foo.class);
foos.add(f);
}
}
但是您需要確保Foo類成員名稱與json屬性名稱匹配。 您的不是因為大寫。 也就是說,您需要將Foo類更改為如下形式:
class Foo {
int id;
String name;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.