1

I have random JSON strings that contain string values when they are really numbers but I have no way to know what fields they might be when coming into my system.

For example:

{
   "some_key":"1234",
   "another_key":{
      "sub_key":"4243",
      "a_string":"this is a valid string and should not be converted"
   }
}

Does any one know of a simple way to try to convert json values into integers using json4s?

4

2 回答 2

2

Figured it out. This piece of code does just what I need:

private def convertNumbers(json: JValue) =
  json.transformField {
    case JField(k, v) ⇒ k → (v match {
      case s: JString ⇒ Try(JInt(s.s.toInt)).getOrElse(s)
      case o          ⇒ o
    })
  }
于 2014-07-17T16:57:09.807 回答
1

Unfortunately, because these keys are encoded as strings, you'll need to convert them. So, you could do something like this:

val json = parse("""{some_key":"1234"}""")
Try((json \ "some_key").values.toString.toInt) match {
  case Success(i) => JInt(i)
  case Failure(i) => s
}

This will return a JInt if it can convert to an Int, or JString otherwise

于 2014-07-17T10:03:34.383 回答