Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing an interface using Gson?

Tags:

gson

I'm trying to use Gson with an interface:

public interface Photo {
    public int getWidth();
}

public class DinosaurPhoto implements Photo {
    ...
}

public class Wrapper {
    private Photo mPhoto; // <- problematic
}

... 

Wrapper wrapper = new Wrapper();
wrapper.setPhoto(new DinosaurPhoto());
Gson gson = new Gson();
String raw = gson.toJson(wrapper);  

// Throws an error since "Photo" can't be deserialized as expected.
Wrapper deserialized = gson.fromJson(raw, Wrapper.class);

Since the Wrapper class has a member variable that is of type Photo, how do I go about deserializing it using Gson?

Thanks

like image 587
user291701 Avatar asked Jun 27 '12 22:06

user291701


1 Answers

Custom deserialization is necessary.

Depending on the larger problem to be solved, either a ["type adapter"] 1 or a "type hierarchy adapter" should be used. The type hierarchy adapter "is to cover the case when you want the same representation for all subtypes of a type".

like image 111
Programmer Bruce Avatar answered Oct 28 '22 20:10

Programmer Bruce