Yadu Krishnan
Yadu Krishnan

Reputation: 3522

Parse json string into scala case class in java

I have a small spring(mvc) web application. This application has dependency on one scala module, which has a case class MessageCommand. I want to convert the JSON String into MessageCommand Case class using Jackson.

Is this possible?

I am using Spring 4, Jackson-asl 1.9, Scala 2.11 Case class.

Upvotes: 1

Views: 1558

Answers (1)

Jatin
Jatin

Reputation: 31724

Well you can. But you need to tweak some things in case class:

case class Message(@BeanProperty var num:Int, @BeanProperty var name:String){
    def this() = this(-1,null)
}

import org.codehaus.jackson.map.ObjectMapper
import scala.beans.BeanProperty

val mapper = new ObjectMapper
val json = """{"num":1,"name":"Di Caprio"}"""

scala> val user = mapper.readValue(json, classOf[Message])
user: Message = Message(1,Di Caprio)

If you cannot tweak the case class, then it gets a bit difficult and untidy

Upvotes: 2

Related Questions