K
K
kidar22015-03-04 17:37:19
Java
kidar2, 2015-03-04 17:37:19

Java Gson deserialization. How to handle interfaces?

I have these types:

interface IBla
{
  
}

class Bla implement IBla
{
  private int field;
}

class Bla2 implement IBla
{
  private int field;
  private int field2;
}

class Foo
{
  IBla kuku;
}
Serialization of objects of the Foo class proceeds normally.
But here's how to deserialize the received json back? The problem is that you need to somehow explain to gson what type of object to take (Bla or Bla2) in order to properly deserialize. How can I do that?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Moxa, 2015-03-04
@Moxa

there is a wild idea to make Foo typed, I don’t know how correct it will be .. like this

class Foo<T extends IBla>
{
  T kuku;
}

and deserialize like
Foo foo = gson.fromJson(jsonString, new TypeToken<Foo<Bla2>>() {}.getType())

V
Vladimir Smirnov, 2015-03-05
@bobzer

Depends on the implementation you are using. In Jackson it's done like this:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Bla.class, name = "Bla"),
        @JsonSubTypes.Type(value = Bla2.class, name = "Bla2")
})
interface IBla {}

With the @JsonSubTypes annotation, you specify a list of all possible interface implementations.
The JsonTypeInfo specifies that the incoming JSON will have a "type" field that will tell you what type to cast the abstract IBla to when the JSON message is received.

B
bromzh, 2015-03-06
@bromzh

You write your own deserializer/type adapter/instance creator.
https://sites.google.com/site/gson/gson-user-guide...
Then you register all this when you create a Gson object via GsonBuilder

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question