0

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?

Hans73
  • 21
  • 2
  • BEWARE: Json4s is [vulnerable under DoS/DoW attacks](https://github.com/json4s/json4s/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+denial)! – Andriy Plokhotnyuk Jul 01 '20 at 09:50
  • @AndriyPlokhotnyuk Thanks for the warning. This won't be a problem in my case. I use it within a Gatling / test script – Hans73 Jul 02 '20 at 06:57

0 Answers0