0

when I am deserializing a JSON with the following simple code usign json4s

package main.scala

import org.json4s._
import org.json4s.jackson.JsonMethods._

  object Main {

    case class Person(name: String, age: Int)

    def main(args: Array[String]): Unit = {
      val jsValue = parse("""{"name":"john", "age": 28}""")
      implicit val formats = DefaultFormats
      val p = jsValue.extract[Person]
    }
  }

Is giving the following error.

Exception in thread "main" org.json4s.package$MappingException: scala.Predef$.refArrayOps([Ljava/lang/Object;)Lscala/collection/mutable/ArrayOps; Case classes defined in function bodies are not supported.

Does anyone know why it happens?

Michał
  • 2,456
  • 4
  • 26
  • 33
flavio
  • 168
  • 1
  • 9
  • 3
    It seems that the answer is in the error. You should define your case class outside your `Main` object. – Cyrille Corpet May 28 '17 at 23:26
  • Unfortunately it happens also when I do it in an external object like: object Main { case class Person(name: String, age: Int) } – flavio May 29 '17 at 07:53
  • You don't need to define it in an object. A case class can be defined as top level in a package. – Cyrille Corpet May 29 '17 at 08:24
  • 1
    I tried out your code and it worked for me. I used version 3.3.0, maybe you've got an old version of jackson, or different scala version - try change the lib version – Bruce Lowe May 29 '17 at 15:45
  • Thank you it was a library issue - not really sure what, but upgraded Scala SDK to the latest version and worked fine :) – flavio May 29 '17 at 20:25
  • https://stackoverflow.com/questions/75947449/run-a-scala-code-jar-appear-nosuchmethoderrorscala-predef-refarrayops – Dmytro Mitin Apr 07 '23 at 04:51

1 Answers1

2

As it came out in the comments, this limitation has been surpassed with newer version. However you could have made this work by moving the case class definition outside your main:

package main.scala

import org.json4s._
import org.json4s.jackson.JsonMethods._

// here!
case class Person(name: String, age: Int)

object Main {

  def main(args: Array[String]): Unit = {
    val jsValue = parse("""{"name":"john", "age": 28}""")
    implicit val formats = DefaultFormats
    val p = jsValue.extract[Person]
  }

}
stefanobaghino
  • 11,253
  • 4
  • 35
  • 63
  • 1
    The problem seemed to be purely related to json4s - scala - jdk versions, I tried by myself to do this change as well but with no success. Anyway usually what you suggested seems to be the right solution :) – flavio May 31 '17 at 10:54
  • Ok, sorry, I noticed that in a comment you wrote it was still inside the `Main` object. Good to know anyway. – stefanobaghino May 31 '17 at 11:07