I'm parsing this string using JSON.parseFull(). This method is really convenient to me because I need to get a Map
val jStr = """{"wt":"json","rows":500}"""
println( JSON.parseFull(jStr) )
here's the output:
Some(Map(wt -> json, rows -> 500.0)) // ´rows´ as Double
I'd like to get back an Integer instead of a Double.
Some(Map(wt -> json, rows -> 500)) // ´rows´ as Integer
Is that possible?
From Scala's JSON documentation
The default conversion for numerics is into a double. If you wish to override this behavior at the global level, you can set the globalNumberParser property to your own (String => Any) function. If you only want to override at the per-thread level then you can set the perThreadNumberParser property to your function
in your case:
val myConversionFunc = {input : String => Integer.parseInt(input)}
JSON.globalNumberParser = myConversionFunc
scala> println( JSON.parseFull(jStr) )
Some(Map(wt -> json, rows -> 500))
The default conversion of numerics is Double in scala
Basically you need to set the default number parser globalNumberParser
to int
first
JSON.globalNumberParser = {
in =>
try in.toInt catch { case _: NumberFormatException => in.toDouble}
}
val jStr = """{"wt":"json","rows":500}"""
println( JSON.parseFull(jStr) )
Output:
Some(Map(wt -> json, rows -> 500)) // ´rows´ as Integer