Is there a simpler approach to providing a default value for an invalid or blank string field when parsing JSON with argonaut?
I am using Argonaut to parse JSON strings. There is a requirement: if any field is not provided or is empty or empty, replace it with the string "not attached".
I have a solution, but it seems very complicated:
case class User(name: String, home: String)
implicit def UserDecodeJson: DecodeJson[User] = DecodeJson(j => for {
name <- (j --\ "name").as[BlankAsNonSupplied]
home <- (j --\ "home").as[BlankAsNonSupplied]
} yield User(name.value, home.value))
case class BlankAsNonSupplied(value: String)
implicit def BlankAsNonSuppliedDecodeJson: DecodeJson[BlankAsNonSupplied] = DecodeJson.withReattempt(a => {
val v = a.success.map(_.focus).flatMap(_.string)
.filterNot(_.trim.isEmpty)
.map(BlankAsNonSupplied.apply).getOrElse(BlankAsNonSupplied("not supplied"))
DecodeResult.ok(v)
})
You can see that it is BlankAsNonSuppliedDecodeJson
very complex and difficult to understand. Is there a way to make this (or the whole example) easier?
+3
source to share
No one has answered this question yet
Check out similar questions: