Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

scala - Play Framework - add a field to JSON object

I have a problem with adding a field to Json object in Play Framework using Scala:

I have a case class containing data. For example:

case class ClassA(a:Int,b:Int)

and I am able to create a Json object using Json Writes:

val classAObject = ClassA(1,2)
implicit val classAWrites= Json.writes[ClassA]
val jsonObject = Json.toJson(classAObject)

and the Json would look like:

{ a:1, b:2 }

Let's suppose I would like to add an additional 'c' field to the Json object. Result:

{ a:1, b:2, c:3 }

How do I do that without creating a new case class or creating my Json object myself using Json.obj? I am looking for something like:

jsonObject.merge({c:3}) 

Any help appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JsObject has a + method that allows you to add fields to an object, but unfortunately your jsonObject is statically typed as a JsValue, not a JsObject. You can get around this in a couple of ways. The first is to use as:

 scala> jsonObject.as[JsObject] + ("c" -> Json.toJson(3))
 res0: play.api.libs.json.JsObject = {"a":1,"b":2,"c":3}

With as you're essentially downcasting—you're telling the compiler, "you only know that this is a JsValue, but believe me, it's also a JsObject". This is safe in this case, but it's not a good idea. A more principled approach is to use the OWrites directly:

scala> val jsonObject = classAWrites.writes(classAObject)
jsonObject: play.api.libs.json.JsObject = {"a":1,"b":2}

scala> jsonObject + ("c" -> Json.toJson(3))
res1: play.api.libs.json.JsObject = {"a":1,"b":2,"c":3}

Maybe someday the Json object will have a toJsonObject method that will require a OWrites instance and this overly explicit approach won't be necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...