json - trouble extracting recursive data structures in scala with json4s -
json - trouble extracting recursive data structures in scala with json4s -
i have json format consists of map -> map -> ... -> int arbitrary number of maps per key. keys strings , leaf types ints. depth of map construction varies per key in map. example, key "a" type map[string, int] , key "b" type map[string, map[string, int]]. know can parse format map[string, any], i'm trying preserve types create these structures easier merge later in code.
i can't seem define nested construction in such way not throw error on json4s extract. i'm not quite sure if problem in construction definition or if i'm not doing json extract correctly.
here code
sealed trait nestedmap[a] case class elem[a](val e : a) extends nestedmap[a] case class nmap[a](val e : map[string, nestedmap[a]]) extends nestedmap[a] // xxx next line doesn't seem help or wound case class empty extends nestedmap[nothing] implicit val formats = defaultformats val s = "{\"1\": 1, \"2\": 1, \"3\": {\"4\": 1}}" val b = parse(s).extract[nmap[int]]
here error comes up
org.json4s.package$mappingexception: no usable value e expected object got jnothing
do need add together value extends nestedmap? going exclusively wrong? help much appreciated.
by default, tree yours expanded to different json.
import org.json4s._ import org.json4s.native.serialization import org.json4s.native.serialization.{read, write} import org.json4s.native.jsonmethods._ implicit val formats = serialization.formats(notypehints) sealed trait elem case class leaf(val e:int) extends elem case class tree(val e:map[string, elem]) extends elem scala> val t = tree(map("1"->leaf(1),"2"->leaf(2),"3"->tree(map("4"->leaf(4))))) t: tree = tree(map(1 -> leaf(1), 2 -> leaf(2), 3 -> tree(map(4 -> leaf(4))))) scala> write(t) res0: string = {"e":{"1":{"e":1},"2":{"e":2},"3":{"e":{"4":{"e":4}}}}} scala> val jt = parse(res0) jt: org.json4s.jvalue = jobject(list((e,jobject(list((1,jobject(list((e,jint(1))))), (2,jobject(list((e,jint(2))))), (3,jobject(list((e,jobject(list((4,jobject(list((e,jint(4)))))))))))))))) scala> val s = """{"1":1,"2":2, "3":{"4":1}}""" s: string = {"1":1,"2":2, "3":{"4":1}} scala> val st = parse(s) st: org.json4s.jvalue = jobject(list((1,jint(1)), (2,jint(2)) (3,jobject(list((4,jint(1)))))))
json scala json4s
Comments
Post a Comment