ObjectMapper - десериализация плоского объекта - PullRequest
0 голосов
/ 20 ноября 2018

У меня есть следующий класс, который внутренне использует HashMap:

open class I18n<T> {

    var i18n: MutableMap<LanguageEnum, T?> = mutableMapOf()
        @JsonAnyGetter get

    fun add(lang: LanguageEnum, value: T?) {
        i18n[lang] = value
    }

    // ...
}

Благодаря аннотации @JsonAnyGetter, когда я сериализую это в Json, у меня есть следующий формат:

{
    "pt": "Texto exemplo",
    "en": "Example text"
}

вместо

{
    i18n: {
        "pt": "Texto exemplo",
        "en": "Example text"
    }
}

Теперь мне нужно вернуться обратно.У меня есть HashMap, содержащий ключ языка, и мне нужно десериализовать его в мой I18n объект.

Предостережение заключается в том, что я делаю это среди множества размышлений и абстракций, и было бы очень приятноесли бы это могло работать так:

// Here I am going through the fields of a given POJO. 
// One of those fields is a I18n type. 
// My model variable is a Map containing the same keys as my POJO field's name, so I'm basically trying to map them all
for (f in fields) {
    if (model.containsKey(f.name)) {

        // when f.type is I18n, value is a HashMap<string, string>
        val value = model[f.name]
        f.isAccessible = true

        // when f.type is I18n.class, the field is set to an empty instance of I18n because it could not desserialize
        f.set(dto, mapper.convertValue(value, f.type))
        f.isAccessible = false
    }
}

Я бы не хотел делать такие вещи, как:

if (f.type === I18n.class) {
    // Special treatment
}

Есть идеи?Заранее спасибо.

...