Scala - Couldn't remove double quotes for "{}" braces while building Json
import scala.util.Random
import math.Ordered.orderingToOrdered
import math.Ordering.Implicits.infixOrderingOps
import play.api.libs.json._
import play.api.libs.json.Writes
import play.api.libs.json.Json.JsValueWrapper
val data1 = (1 to 2)
.map {r => Json.toJson(Map(
"name" -> Json.toJson(s"Perftest${Random.alphanumeric.take(6).mkString}"),
"domainId"->Json.toJson("343RDFDGF4RGGFG"),
"value" ->Json.toJson("{}")))}
val data2 = Json.toJson(data1)
println(data2)
Result : [{"name":"PerftestpXI1ID","domainId":"343RDFDGF4RGGFG","value":"{}"},{"name":"PerftestHoZSQR","domainId":"343RDFDGF4RGGFG","value":"{}"}]
Expected : "value":{}
[{"name":"PerftestpXI1ID","domainId":"343RDFDGF4RGGFG","value":{}},{"name":"PerftestHoZSQR","domainId":"343RDFDGF4RGGFG","value":{}}]
Please suggest a solution
You are giving it a
Stringso it is creating a string in JSON. What you actually want is an empty dictionary, which is aMapin Scala:More generally you should create a
case classfor the data and create a customWritesimplementation for that class so that you don't have to callJson.toJsonon every value.Here is how to do the conversion using only a single
Json.toJsoncall:The
valuefield can be a standard type such asBooleanorDouble. It could also be anothercase classto create nested JSON as long as there is a similarJson.formatline for the new type.More complex JSON can be generated by using a custom
Writes(andReads) implementation as described in the documentation.