I use the JSON4S library in Scala to do some parsing of serialised JSON strings to objects to have a simple JSON validator.
case class MyObject (
productName: Option[String],
amount: Int,
price: Double
)
def jsonCheck[T](data: String)(implicit m: Manifest[T]): Boolean = {
implicit val formats: DefaultFormats = new DefaultFormats {
override val strictOptionParsing: Boolean = true
}
try {
parse(data).extract[T]
true
} catch {
case _: MappingException => false
}
}
This works fine to check whether all required fields are available. Both
jsonCheck[MyObject]("""{"productName":"example","amount":10,"price":25.25}""")
and
jsonCheck[MyObject]("""{"amount":10,"price":25.25}""")
return true
as expected.
However, when I provide a double-value for the amount field, the functions also returns true
where I expect a false
.
jsonCheck[MyObject]("""{"amount":10.5,"price":25.25}""")
Is there a way to return false from the jsonCheck function if the field-type doesn't match?