Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange deserializing problems with generic types using Scala and Jackson and java.lang.Integer or scala.Int
    primarykey
    data
    text
    <p>We all know that generic types are subject to type erasure under Java and Scala. But we ran into a strange problem in Scala using Jackson and the Scala Jackson Module.</p> <p>I created a small test to show the problem.</p> <pre><code>import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule object GenericTest { case class TestWithInt(id: Option[Int]) case class TestWithInteger(id: Option[Integer]) def main(args: Array[String]) { val mapper = new ObjectMapper() mapper.registerModule(DefaultScalaModule) // Test with scala's Int val test = mapper.readValue[TestWithInt]("""{ "id" : 5 }""", classOf[TestWithInt]) print("Test 1: ") println(test.id.get + 1) val test2 = mapper.readValue[TestWithInt]("""{ "id" : "5" }""", classOf[TestWithInt]) print("Test 2: ") try { println(test2.id.get + 1) } catch { case e: ClassCastException =&gt; println(e.getMessage) } // Test with java.lang.Integer val test3 = mapper.readValue[TestWithInteger]("""{ "id" : 5 }""", classOf[TestWithInteger]) print("Test 3: ") println(test3.id.get + 1) val test4 = mapper.readValue[TestWithInteger]("""{ "id" : "5" }""", classOf[TestWithInteger]) print("Test 4: ") println(test4.id.get + 1) } } </code></pre> <p>The output of the above is:</p> <pre><code>Test 1: 6 Test 2: java.lang.String cannot be cast to java.lang.Integer Test 3: 6 Test 4: 6 </code></pre> <p>Where does this different kind of behaviour come from? Generic Type Erasure, Jackson, Jackson Scala Module?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload