Skip to content

Unexpected behavior when converting large numeric values to Int  #160

@archevel

Description

@archevel

When converting an json object with a large number as one of its values to a case classes that can only hold an ´Int´ there is no error. I would expect some exception to be thrown in this case since it could cause some really strange behaviour and hard to detect errors (for instance if the number is an id of some kind).

scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Foo(num:Int)
object Foo {
  import spray.json.DefaultJsonProtocol._
  implicit val format = jsonFormat1(Foo.apply)
}

// Exiting paste mode, now interpreting.

defined class Foo
defined object Foo

scala> import spray.json.pimpString
import spray.json.pimpString

scala> """{"num":999999999999999999999999}""".parseJson.convertTo[Foo]
res1: Foo = Foo(-1593835521)

scala> s"""{"num":${Long.MaxValue}}""".parseJson.convertTo[Foo]
res2: Foo = Foo(-1)

The problem also occurs if we just convert to Ints.

scala> import spray.json.DefaultJsonProtocol._
import spray.json.DefaultJsonProtocol._

scala> import spray.json.pimpString
import spray.json.pimpString

scala> "999999999999999999999999".parseJson.convertTo[Int]
res1: Int = -1593835521

scala> s"${Long.MaxValue}".parseJson.convertTo[Int]
res2: Int = -1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions