Is it possible to make Scala JSON.parseFull () not treat integers as decimal numbers?

I am parsing this string using JSON.parseFull (). This method is really convenient for me because I need to get a map

val jStr = """{"wt":"json","rows":500}""" println( JSON.parseFull(jStr) ) 

here is the conclusion:

 Some(Map(wt -> json, rows -> 500.0)) // ´rows´ as Double 

I want to return Integer instead of Double.

 Some(Map(wt -> json, rows -> 500)) // ´rows´ as Integer 

Is it possible?

+6
source share
2 answers

From Scala JSON Documentation

The default conversion for numbers to double. If you want to override this behavior globally, you can set the globalNumberParser property of your own (String => Any). If you only want to override the level on the thread, you can set the perThreadNumberParser property for 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))

+7
source

Converting Default Double Numbers to scala

Basically you need to set the default 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 
+3
source

Source: https://habr.com/ru/post/954357/


All Articles