Gson can't deserialize inherited class?

gson, java, json

Solution

The issue is that your JSON represents an Object that contains another object you're interested in while your Java is just a single object.

You can actually just write deserializers for each type and use them once you determine the `MessageType`:

public static void main(String[] args)
{
    Gson gson = new GsonBuilder().registerTypeAdapter(TimeData.class, new TimeDataDeserializer()).create();
    String json = "{\"MessageType\":\"TimeData\",\"TimeData\":{\"hh\":12,\"mm\":13,\"ms\":15,\"ss\":14}}";
    JsonMessage message = gson.fromJson(json, JsonMessage.class);

    switch(message.MessageType)
    {
        case TimeData:
            TimeData td = new GsonBuilder()
                            .registerTypeAdapter(TimeData.class, new TimeDataDeserializer())
                            .create()
                            .fromJson(json, TimeData.class);
            td.MessageType = message.MessageType
            System.out.println(td.hh);
            break;
        default:
            break;
    }
}

class TimeDataDeserializer implements JsonDeserializer<TimeData>
{
    @Override
    public TimeData deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)  
        throws JsonParseException
    {
        JsonObject jo = je.getAsJsonObject().getAsJsonObject("TimeData");
        Gson g = new Gson();
        return g.fromJson(jo, TimeData.class);
    }
}

Problem

I have a simple Json structure like: ``` {"MessageType":"TimeData","TimeData":{"hh":12,"mm":13,"ms":15,"ss":14}} ``` and I devised the following classes to deserialize it: ``` public class JsonMessage { public enum MessageTypes{ WhoAreYou, TimeData } JsonMessage(){ } public MessageTypes MessageType; } ``` ``` class TimeData extends JsonMessage{ int hh; int mm; int ss; int ms; TimeData() { } } ``` I need to split deserialization into tow phases: 1- deserialize to read the `MessageType`. 2- proceed with the rest of deserialization based on the `MessageType` The code is straightforward: ``` public void dispatch(Object message, IoSession session) { Gson gson = new Gson(); JsonMessage result = gson.fromJson(message.toString(), JsonMessage.class); System.out.println(result.MessageType.toString()); switch (result.MessageType) { case WhoAreYou:{ //..... break; } case TimeUpdate: TimeData res = new Gson().fromJson(message.toString(), TimeData.class); System.out.println(res.hh); break; default:break; } } ``` My Program can enter the correct `switch-case`(which is `TimeUpdate`) but it doesn't parse it correctly (The println prints 0 instead of 12) where do you think I have done something wrong? thank you

Original source

Related problems