Reputation: 473
I have a json which has some null value in it, I just want to replace that null value with an empty string using play json.
Sample json:
{
"featureLength": 348.4256690782206,
"projectName": null,
"total_Feature_Length": 348.43
}
Upvotes: 1
Views: 971
Reputation: 2796
We use two ways to "receive" JSON: the "ad hoc" way, and the "case class" way. In the ad hoc way you might have something like:
val projectName = (json \ "projectName").asOpt[String].getOrElse("")
which would accept a string or null and give you a string in the projectName variable. In the "case class" way, we define a Reads converter, say for case class Feature
, and then
implicit val reads: Reads[Feature] = {
((__ \ "featureLength").read[Double] and
(__ \ "projectName").read[Option[String]] and
(__ \ "total_Feature_Length").read[Double]) ((length:Double, projectName:Option[String], totalLength:Double) =>
Feature(length,projectName.getOrElse(""),totalLength))
}
which will convert the input to your case class and again, the getOrElse
ensures that the incoming projectName, whether a string or a null will result in a string thereafter.
Upvotes: 1