Reputation: 2887
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
Upvotes: 1
Views: 2329
Reputation: 21125
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:
Upvotes: 1
Reputation: 13570
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);
}
Upvotes: 0