1

I have a JSON object and part of it I am mapping to AnyRef due to the fact that it might contain the variable key/value pairs. I treat that section as junk drawer. But I have to add "id" and random key to that AnyRef object. How can I do that?

I have tried to do the following but the map is stored and the generated JSON does not look right.

Here is my example:

val map1 = requestStateChange.cloudModel.asInstanceOf[Option[Map[String, AnyRef]]]
val newModel = List(("id", java.util.UUID.randomUUID().toString)).toMap[String, AnyRef] ++ map1.get

What I really want to have generates is something like this:

{   
  "model": {
    "id": "c9725317-e2e5-43e8-876e-5ab6a16b951d"
    "version": "v1",
    "location": "...",
    "type": "...",
    "data": {
        "id": "9520146"
    }
  }
}

Appreciate for your help.

Ben Reich
  • 16,222
  • 2
  • 38
  • 59
Roman Kagan
  • 10,440
  • 26
  • 86
  • 126

1 Answers1

4

Don't reinvent the wheel here. As a rule of thumb, idiomatic Scala avoids using types like Any when possible. There are plenty of libraries that let you deal with JSON easily. You might consider Play JSON. If you were using that library, you could do something like:

val myJsonString = """{ "foo" : "bar" }"""
val map = Json.parse(myJsonString).as[JsObject]
val newMap = map + ("id" -> JsNumber(123)) //Adding a new property is easy now
Json.stringify(newMap) // {"foo":"bar","id":123}, as desired

You can read more about Play JSON here. You can read about other alternative to Play JSON here.

If you do need to instantiate an AnyRef, you can assign any type to an AnyRef except the basic value types:

Map(1 -> "a") : AnyRef

You might consider using Any instead of AnyRef, which is even more general, and will allow you to use basic value types as well, such as 1 : Any. You can read more about the relationship between Any, AnyRef, and AnyVal here. For your example, you could do something like this:

val map1 : Map[String, Any] = Map("model" -> Map("version" -> "v1"))
val model = map1("model").asInstanceOf[Map[String, Any]]
val newModel = model.updated("id", 123)
val newMap = map1.updated("model", newModel)
Community
  • 1
  • 1
Ben Reich
  • 16,222
  • 2
  • 38
  • 59