简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM