10

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?

Max
  • 2,508
  • 3
  • 26
  • 44

2 Answers2

8

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

Alaeddine
  • 1,571
  • 2
  • 22
  • 46
Diego Basch
  • 12,764
  • 2
  • 29
  • 24
  • How bad! That means I need to treat all the numbers as they were Integer or Decimal... For the case I posted as example is Ok, but what if I had to deal with a mixed case of numbers? It would be great if I could get non fractional as Integers and fractional as Decimal. I guess I can't rely on JSON.parseFull() and I need to write some extra code in order to get what I want. – Max Sep 22 '13 at 22:04
  • Not necessarily. If floating point numbers always have a dot, you could write a conversion function that returned a Float for "100.0" and an Int for "100" – Diego Basch Sep 22 '13 at 22:43
  • Scala's JSON documentation link Not found. – Alaeddine Oct 01 '15 at 12:27
6

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
Suma
  • 33,181
  • 16
  • 123
  • 191
Alaeddine
  • 1,571
  • 2
  • 22
  • 46