Search code examples
javajacksonjackson2

Jackson create object by class name


Is there opportunity to read from json class name and create and object?

Here is what I mean:

I have an interface

public interface Converter {
    void process();
}

Next I also have some data class

public class Source {
    private String service;
    private String path;
    private Converter converter;
}

And a class that implements Converter interface

public class DataConverter implements Converter {
    public void process() {
        //some code here
    }
}

Last but not least. This is part of my json:

"source": {
    "service": "VIS",
    "path": "/",
    "converter": "DataConverter"
}

So the idea is while reading Json via Jackson's mapper.readValue create a DataConverter so it will be available from the Data class via getter.

Thanks!


Solution

  • You can achieve this by writing custom serialisers and deserialisers, and then annotating the field in your Source class. To do this you need to implement the Converter interface. The documentation suggests:

    NOTE: implementors are strongly encouraged to extend StdConverter instead of directly implementing Converter, since that can help with default implementation of typically boiler-plate code.

    So what you want to do is something like this for the custom Serialiser:

    public class ConverterSerializer extends StdConverter<Converter, String> {
    
    @Override
    public String convert(Converter value) {
        if(value instanceof DataConverter) {
            return "DataConverter";
        } ...
    
        return "";
    }
    

    }

    And then annotate the value with @JsonSerialize:

    @JsonSerialize(using = ConverterSerializer.class)
    private Converter converter;
    

    The same applies for deserialising but you would implement an StdConverter<String,Converter> for which the convert method will take a String and return a Converter. You would then annotate the converter field with @JsonDeserialize and reference the converter.