Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON deserialization : how to know the objects?

Tags:

java

gson

gwt

I try to use gson library to deserialize a flow of objects sent to me. In all examples i've seen, when the method fromJson is called, we already know what type of object we expect to have.

In my case, I receive a flow of different objects and i'd like to know the best way to know the classes of objects before deserialize them.

{ A : {...}, B : { B1 : {...}, B2 : {...} }, C : {...} }

In this example, I'd like to have a way to know that 3 objects have been sent to me : A.class, B.class and C.class

Thanks

like image 693
Antonio Lokas Avatar asked Dec 27 '22 22:12

Antonio Lokas


1 Answers

The documentation contains examples of deserializations using arbitrary classes or in two passes (first general deserialization in a collection, then content deserialization).

This exemple looks exactly like what you need. You could adapt it to use

JsonObject obj = parser.parse(json).getAsJsonObject();

to get a JsonObject instead of an array so that you can iterate on all properties (using entrySet) and deserialize according to the names (a = gson.fromJson(myjsonelement, A.class);) by simply mapping names to classes.

like image 118
Denys Séguret Avatar answered Jan 04 '23 05:01

Denys Séguret