jeudi 18 juillet 2019

Generic class with only one field?

I have an interesting problem that I'm having trouble coming up with a clean solution for. My application reads collections of json objects that it needs to deserialize to this or that class type based on a field in the json itself. I have no control over the json structure or how it gets to my application.

I've created models for each type of object that could be coming to the application and I've reached a point where I'm trying to build a service that pulls out the 'type' field and then uses ObjectMapper to deserialize the json to the appropriate Model.

Json example:

{
    "message_type" : "model1"
    "other data" : "other value"
    ...
}

Models:

public class Model1 {
    ...
}

public class Model2 {
    ...
}

Service?:

public class DynamicMappingService {

    public ???? mapJsonToObject(String json) {
        String type = pullTypeFromJson();

        ???
    }

    private String pullTypeFromJson() {...}
}

I don't want a massive switch statement that says "If type value is this then deserialize to that" but I'm struggling to come up with something clean that does that. I thought maybe a generic model class where the generic parameter is the Model Type and the only field is the instance of that model type but that doesn't seem right either and I'm not sure what that buys me. I could also have some sort of empty abstract class that all of the models extend but that seems horrible too. How do I deal with this? Extra points for an example.

Aucun commentaire:

Enregistrer un commentaire