Search code examples
scalaplay-json

Efficient parsing of Byte Array to Json Object


Assuming I have a byte array in json format (e.g., "{"key":"a0998df", "someVal":45}") and I want to convert it to a json object. The easiest thing to do (using the play-json lib) is something like this:

val byteArr = ....
val str = new String(byteArr)
val jsObject = Json.parse(str).as[JsObject]

But I was thinking if there is a faster way to get the json object directly from a byte array without creating a String object of the whole message first (whether in Java or Scala). Thanks in advance!


Solution

  • The Json.parse method is overloaded, you can directly pass the byte array into it:

    val byteArr = ....
    val jsObject = Json.parse(byteArr).as[JsObject]
    

    See https://www.playframework.com/documentation/2.8.x/api/scala/play/api/libs/json/Json$.html#parse(input:Array[Byte]):play.api.libs.json.JsValue