Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make Scala's JSON.parseFull() not to treat Integers as Decimals?

Tags:

json

scala

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?

like image 238
Max Avatar asked Sep 22 '13 16:09

Max


2 Answers

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))

like image 63
Diego Basch Avatar answered Oct 23 '22 17:10

Diego Basch


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
like image 6
Alaeddine Avatar answered Oct 23 '22 18:10

Alaeddine