If I am working with json4s (using Jackson bindings):
scala> import org.json4s._
scala> import org.json4s.jackson.JsonMethods._
scala> parse(""" { "numbers" : [1, 2, 3, 4] } """)
res0: org.json4s.JsonAST.JValue =
JObject(List((numbers,JArray(List(JInt(1), JInt(2), JInt(3), JInt(4))))))
How can I convert a given org.json4s.JsonAST.JValue
like the above to a com.fasterxml.jackson.databind.JsonNode
?
For why I want to do this: I want to validate JValue
s against JSON Schemas, using the excellent json-schema-validator Java library, which takes JsonNode
s as arguments.
I am looking for some kind of equivalent to the Play Framework's handling of JsValue
<> JsonNode
interop.
Since Json4s 3.2.11-SNAPSHOT there are two methods which can convert between JValue and JsonNode:
asJsonNode(jv: JValue): JsonNode
converts a JValue to a JsonNodefromJsonNode(jn: JsonNode): JValue
converts a JsonNode to a JValueHere is an example how to use it:
import org.json4s._
import org.json4s.jackson.JsonMethods._
val jv = parse(""" { "numbers" : [1, 2, 3, 4] } """)
val jn = asJsonNode(jv)
println(jn)
// {"numbers":[1,2,3,4]}
val jv2 = fromJsonNode(jn)
println(jv2)
// JObject(List((numbers,JArray(List(JInt(1), JInt(2), JInt(3), JInt(4))))))