0

I have a dropwizard application that parses conf files to construct the application's configuration.

base.conf file has:

country: USA

in the configuration java file:

@NotNull
private MyObject country;

MyObject is not an enum in this case. It is a regular object.

How can I configure it to have dropwizard automatically convert the parsed string value to MyObject based on some logic I define, like:

MyObject convertStringToMyObject(String value) {
    if (value.equals("USA") {
        return new MyObject("+1", "North America", "USA");
    }
}

This is obviously just the simplest dumb sample I could think of for what I'm trying to achieve.

Hani
  • 21
  • 3
  • Dropwizard uses Jackson, right? You should be able to add a custom deserializer: https://stackoverflow.com/a/19167145/8681 – Jorn Jun 13 '23 at 07:45
  • that's a good start, but the problem is that MyObject is a class in a library i dont own – Hani Jun 13 '23 at 17:23

1 Answers1

1

There are a couple of different ways you might want to consider when approaching:

(1) Use an enumeration in the configuration and then provide a mapping to the MyObject class which controls the instantiation of the fields driven by the country. This will make it clear which countries are supported (and for which you have mappings).

public class MyConfig extends Configuration {

    enum Country {
        USA;

        MyObject toObject() {
            switch (this) {
                case USA:
                    return new MyObject("+1", "North America"...);
            }
            ...
        }
    }
    
    public Country country;
}

(2) Register a custom deserialiser. Even if you don't own the MyObject class you will still be able to register a custom deserialiser either directly on the ObjectMapper or by using the JsonDeserializer(using = MyObjectDeserializer) annotation on the field in your application configuration (rather than on the MyObject class declaration which as you say - is not editable by you) - example:

public class MyConfig extends Configuration {

    @JsonDeserialize(using = MyObjectDeserializer.class)
    public MyObject country;
}
snowy
  • 11
  • 1