How to merge a JsValue to JsObject in flat level

前端 未结 2 751
囚心锁ツ
囚心锁ツ 2021-02-05 13:59

I have two JsValue created from case class, i.e. Book and Book detail

val bookJson = Json.tojson(Book)
val bookDetailJson = Json.tojson(BookDetail)
2条回答
  •  执念已碎
    2021-02-05 14:16

    JsObject is subtype of JsValue.

    JsValue can be simple converted to the JsObject using as or asOpt methods from JsValue. Example:

    val someJsValue = ....
    val asObject:JsObject = someJsValue.as[JsObject]
    val asObjectMaybe:Option[JsObject] = v.asOpt[JsObject]
    

    In the case of JsArray you can not use above code. If you use play and parse JSON with array, then Json.toJson(...) produces JsValue which is JsArray actually. You need to convert JsArray as following:

    val someJsValueButArray = ....
    val asJsArray:JsArray = Json.toJson(someJsValueButArray).as[JsArray]
    val asSeqOfJsObjects:Seq[JsObject] = asJsArray.value.map(_.as[JsObject])
    

提交回复
热议问题