Search code examples
scalagsonobjectmapper

Map JSON String to JsonObject


I have a JSON string like

{
    "key1": "value1",
    "definition": {
     // JSON content here
    }
}

"definition" key in JSON can contains JSONArray, JSONObject. For example, it can have

"key2" : ""

or

"key2" : {}

or

"key2" : []

To accommodate this, I have created corresponding Scala class like

import com.google.gson.JsonObject
class JsonData {
  var key1: String = _
  var definition: JsonObject = _
}

While mapping JSON string to class JsonData, I am getting "definition" in JsonData instance as empty.

Sample code:

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.google.gson.JsonObject

object TestMe {

  val mapper = new ObjectMapper with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def main(args: Array[String]): Unit = {
    val jsonString = "{\"key1\": \"value1\",\"definition\": {\"key2\" : \"abc\"}}"
    val data = mapper.readValue[JsonData](jsonString)
    println(data.definition.getAsJsonObject()) //empty

    val jsonString1 = "{\"key1\": \"value1\",\"definition\": {\"key2\" : {\"key3\" : \"\"}}}"
    val data1 = mapper.readValue[JsonData](jsonString1)
    println(data1.definition.getAsJsonObject()) //empty

    val jsonString2 = "{\"key1\": \"value1\",\"definition\": {\"key2\" : [\"a\",\"b\"]}}"
    val data2 = mapper.readValue[JsonData](jsonString2)
    println(data2.definition.getAsJsonObject()) //empty
  }

  class JsonData {
    var key1: String = _
    var definition: JsonObject = _
  }
}

How can I read JSON string and map it to class which has one of its attribute type of JsonObject?

Versions:

Scala : 2.11
Jackson-core = 2.6.x;
Gson = 2.6.x;
Jackson-databind = 2.6.x;
Jackson-module-scala = 2.6.5;

Solution

  • I would use com.fasterxml.jackson.databind.JsonNode instead of using Google's Gson JsonObject class. Using Jackson's own classes should make it pretty trivial. Although you may just map to a Map[String, Any] instead for this kind of flexibility, unless you really need it to still be in Json.