Search code examples
javajsonscalaplayframeworkplay-json

how to convert play.api.libs.json.JsValue to org.json.JSONObject


how to convert play jsObject to JSONObject?

example :

val samplePlayJson = Json.obj(
  "name" -> "Watership Down",
  "location" -> Json.obj("lat" -> 51.235685, "long" -> -1.309197),
  "residents" -> Json.arr(
    Json.obj(
      "name" -> "Fiver",
      "age" -> 4,
      "role" -> JsNull
    ),
    Json.obj(
      "name" -> "Bigwig",
      "age" -> 6,
      "role" -> "Owsla"
    )
  )
)

when I tired to pass above samplePlayJson to a Java api that accepts JSONObject I got type mismatch error

type mismatch;
 found   : play.api.libs.json.JsObject
 required: org.json.JSONObject

how to convert above samplePlayJson to org.json.JSONObject?


Solution

  • You can convert your play.api.libs.json.JsObject to string and make org.json.JSONObject out of it. I didn't find any direct methods to do so.

    new JSONObject(samplePlayJson.toString())