1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

What s the way if I can not edit the scala class? Do I need to write a simple java class and then set the values into the case class from the java class manually?
I googled and found this: github.com/mesosphere/jackson-case-class-module Not sure on how good it is.
I have to do this in Java, not scala. I mean I need to parse a string in java and convert as Scala Case class
I applied the answer you have provided and changed the scala code. that is working fine.
If you are doing it in Java. Things still remain the same: ObjectMapper m = new ObjectMapper(); m.readValue(json, Message.class) :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.