I have an enum defined as
public enum Locale {
EN_US, ES_MX
}
These locale, however, are written as lowercase strings with hyphen as en-us
and es-mx
in data.
Is there a way to map these lowercase strings to corresponding enum constants? Like en-us
to EN_US
?
EDIT Let me provide more information. I have an object of the following class.
public class Song {
private Map<Locale, String> songName;
private int durationMillis;
}
A song's name can vary by Locale. So I create a map for the song's name in various Locales.
I have a JSON file with info on songs. It reads like:
{
"songs": [
{
"songName": {"en-us":"Song name in US english", "es-mx": "Song name in Spanish"},
"durationMillis": 100000
},
{
"songName": {"en-us": "another song name - English"},
"durationMillis": 200000
}
]
}
I define another class.
public class Songs {
private Set<Song> songs;
}
I use FasterXml's ObjectMapper
to load the JSON as an object of Songs
class.
Songs songs = objectMapper.readValue(jsonStr, Songs.class);
This above line crashed right now because ObjectMapper
cannot map en-us
string to Locale.EN_US
.
I can always edit the enum and define it as
public enum Locale {
EN_US("en-us"),
ES_MX("es-mx");
private String value;
Locale(String val){
value = val;
}
}
But I have seen a smarter way somewhere, which converted the lowercase hyphenated string to uppercase underscored literal. Can you point me to that solution?
I need a solution such that FasterXml's ObjectMapper
can map the string to enum.