我有兩種不同類型的JSON,我可能從服務器收到。反序列化時檢查JSON輸入的類型
例如,我可以得到:
{
id:value,
name:value,
time:value
}
或
{
id:value,
name:value,
image:value
}
有沒有一種方法我可以測試,以檢查它是JSON,然後進行進一步的操作?
當前我使用GSON基於JSON輸入創建對象。有沒有辦法可以使用GSON來獲得這個功能?
我有兩種不同類型的JSON,我可能從服務器收到。反序列化時檢查JSON輸入的類型
例如,我可以得到:
{
id:value,
name:value,
time:value
}
或
{
id:value,
name:value,
image:value
}
有沒有一種方法我可以測試,以檢查它是JSON,然後進行進一步的操作?
當前我使用GSON基於JSON輸入創建對象。有沒有辦法可以使用GSON來獲得這個功能?
假設你的JSON是一個JSONObject,你可以做這樣的事情:
if (object.has("time")) {
Time time = gson.fromJson(object, Time.class);
} else {
Image image = gson.fromJson(object, Image.class);
}
如果你出了反序列化上下文(在更多的操作感,不只是gson.fromJson(...)
,在調用點),您可以使用jdebon的答案。如果你要在反序列化過程中檢測到它,你可以創建一個自定義類型適配器(只有當你有一個公共基類時,由於基本的Gson限制禁止綁定java.lang.Object
)。例如:
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (jsonElement, type, context) -> {
final JsonObject jsonObject = jsonElement.getAsJsonObject();
final boolean hasImage = jsonObject.has("image");
final boolean hasTime = jsonObject.has("time");
if (hasImage && hasTime) {
throw new JsonParseException("Cannot handle both image and time");
}
if (hasImage) {
return context.deserialize(jsonElement, Image.class);
}
if (hasTime) {
return context.deserialize(jsonElement, Time.class);
}
throw new JsonParseException("Cannot parse " + jsonElement);
})
.create();
abstract class Base {
final int id = Integer.valueOf(0);
final String name = null;
}
final class Image
extends Base {
final String image = null;
}
final class Time
extends Base {
final String time = null;
}
實施例:
for (final String resource : ImmutableList.of("image.json", "time.json")) {
try (final JsonReader jsonReader = getPackageResourceJsonReader(Q44227327.class, resource)) {
final Base base = gson.fromJson(jsonReader, Base.class);
System.out.println(base.getClass().getSimpleName());
}
}
輸出:
圖片
時間