I'm trying to generate some json using the json4s library which builds json using a dsl based around nested tuple structures. I have a scala Seq that I'd like to be able to convert to a nesting of tuples like so:
// scala Seq
val s = Seq("a", "b", "c", "d")
val rootItem = "id" -> 1234
// desired json
{
"a" : {
"b" : {
"c" : {
"d" : {
"id" : 1234
}
}
}
}
}
If I force it to ignore the types I can produce the desired tuple structure as follows:
// yields ("a", ("b", ("c", ("d", ("id", 1234)))))
s.foldRight[Any](rootItem)(_ -> _)
but because the type of the result is now denoted as Any the implicit conversion that write this to json don't fire (and throw an exception when called explicitly) despite the actual type being correct. I'm at a loss for how to construct this datastructure in a typesafe way. Ideally I'd like a solution that is able to appropriately build up the type, though I understand that it might be impossible since it requires information only available at runtime (the length of the list). I know that scala supports recursive types, which seem to potentially fit the bill but I haven't been able to understand how to work them in this case and don't know if they are safe for a 'real' system.