I have a JSON like this:
{
"switch": "foo",
"items": [
{"type": "one"},
{"type": "two"}
]
}
I want to load it into a structure of classes like that:
case class MyFile(
@JsonProperty("switch") _switch: String,
@JsonProperty("items") _items: JList[Item],
) {
val items: List[Item] = _items.toList
}
case class Item(t: String)
object Item {
@JsonCreator
def create(@JsonProperty("type") _type: String): Item = {
Item(t) // <= conversion
}
}
The trick is that I want to do a conversion of incoming "type" string with some sort of function that will depend on the value of "switch". The simplest example would be something like
def create(@JsonProperty("type") _type: String): Item = {
Item(t + "_" + switchValue)
}
However, I don't seem to find a way to access about parts of JSON tree while inside a parsing (i.e. in constructors or in @JsonCreator
static method).
The only thing I've came with so far is basically a global variable like:
case class MyFile(
@JsonProperty("switch") _switch: String,
@JsonProperty("items") _items: JList[Item],
) {
MyFile.globalSwitch = _switch
val items: List[Item] = _items.toList
}
object MyFile {
var globalSwitch = ""
}
case class Item(t: String)
object Item {
@JsonCreator
def create(@JsonProperty("type") _type: String): Item = {
Item(t + "_" + MyFile.globalSwitch) // <= conversion
}
}
It works, but it's obviously fairly ugly: you can't, for example, parse 2 files with different switch values in parallel, etc. Is there a better solution? For example, maybe I can access some sort of per-ObjectMapper or per-parsing context, where I can store this setting?