I have a question like "style" or "effective scala" here: I have a "FeatureCheck" class that I need to convert to a Json in Play structure.
case class FeatureCheck(val result: Option[Boolean], val missing: Option[Array[String]], val error: Option[String])
I serialize it using my own "records", but my code is very similar to Java code. I would like to serialize each parameter in the validation object only if it is defined (the final object should not have empty values).
def writes(check: FeatureCheck): JsValue = { val builder = Seq.newBuilder[(String, JsValue)] if (check.error.isDefined) { builder += "error" -> JsString(check.error.get) } if (check.missing.isDefined) { builder += "missing" -> Json.toJson(check.missing.get) } if (check.result.isDefined) { builder += "result" -> JsBoolean(check.result.get) } JsObject(builder.result) }
So I was wondering if there is a way to do this without these ugly if-then or even to remove the builder for the sequence.
Thanks for any help or comment.
Clarrifications:
Let's say I just want to send result = true. I want the resulting Json to be:
{"result":true}
and NOT
{ "result": true, "error": null, "missing": [] }
ΙΙ ΙΙ΅ΚΙΙΌΙ ζ± ζΈ
source share