0

i've extracted a map from json. This works so far. As I don't know before parsing which fields are there in the json, I've been using a Map[String, Any]. Every field only consisting of digits is interpreted as a BigInt, which I don't want.

MyCode:

    implicit val formats: DefaultFormats.type = org.json4s.DefaultFormats
    json.extract[Map[String, Any]]

Any way to implicitly make the numbers interpreted as Int or Long?

ScalaNewbie
  • 173
  • 3
  • 12

1 Answers1

1

You did not specify, how the json value is created. If you parse it from a String, than the useBigIntForLong flag does the trick:

import org.json4s.DefaultFormats
import org.json4s.JsonAST._
import org.json4s.native.JsonMethods

object Main {

  def main(args: Array[String]): Unit = {
    implicit val formats: DefaultFormats = DefaultFormats

    val parsedJson = JsonMethods.parse(""" { "a" : 42} """, useBigIntForLong = false)
    parsedJson.extract[Map[String, Any]].foreach {
      case (name, value) => println(s"$name = $value (${value.getClass})")
    }
  }

}

Output:

a = 42 (class java.lang.Long)

If you construct the json value programmatically, than you choose between BigInt and Long directly:

val constructedJson = JObject(
  "alwaysBigInt" -> JInt(42),
  "alwaysLong" -> JLong(55),
)
constructedJson.extract[Map[String, Any]].foreach {
  case (name, value) => println(s"$name = $value (${value.getClass})")
}

Output:

alwaysBigInt = 42 (class scala.math.BigInt)
alwaysLong = 55 (class java.lang.Long)

Example source code

ygor
  • 1,726
  • 1
  • 11
  • 23