How to determine class of object from GSON parse?

*爱你&永不变心* 提交于 2019-12-23 03:53:16

问题


I am parsing JSON string from a byte-array and casting it as an object.

How do I determine the class of the object?

Object objDeserialized = gson.fromJson(jsonFromString, Object.class);
//It could be type Message or RoomDetail

回答1:


gson.fromJson(jsonFromString, Object.class);

In general, this won't work because of Object.class. Gson prohibits overriding the Object class deserialization and uses ObjectTypeAdapter (see the primary Gson constructor as of Gson 2.8.0 and probably much earlier):

// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.FACTORY);

// the excluder must precede all adapters that handle user-defined types
factories.add(excluder);

// user's type adapters
factories.addAll(typeAdapterFactories);

If you want to use Object.class, you have to cast the result to either a primitive wrapper, null, or a List<E> or Map<K,V> -- and make some sort of analysis yourself. The rationale behind it is that you must know the result class in advance to make sure you're getting a proper deserialized object.

The best thing you can do here is making your custom parent super-type (does not really matter if it's a class or an interface), say class Message extends Base and class RoomDetail extends Base, and then registering a JsonDeserializer<Base> implementation to a GsonBuilder which can attempt to detect the real type of the Base instance. After that you can do:

gson.fromJson(jsonSource, Base.class);

See more:

  • Polymorphic objects deserialization:
    • How to parse dynamic json in android with retrofit 2 using annotations
    • How do I parse a nested JSON array of object with a custom Gson deserializer?
    • Json response parser for Array or Object
  • Google Gson extras, never been published as artifacts, but may be an inspiration point for you:
    • https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java



回答2:


If you do not know the type of the JSON you want to parse you could use the JsonParser from the Gson lib to parse the JSON instead of the Gson class directly. e.g.

JsonParser parser = new JsonParser(jsonFromString);
JsonObject obj = parser.parse().getAsJsonObject();

You could then look at the properties of the JsonObject you have created to see what it is. e.g.

if (obj.has("somePropertyNameIKnownIsAMemberOfRoomDetail")) {
    RoomDetail roomDetail = gson.fromJson(jsonFromString, RoomDetail.class);
} else {
    Message message = gson.fromJson(jsonFromString, Message.class);
}


来源:https://stackoverflow.com/questions/43825103/how-to-determine-class-of-object-from-gson-parse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!