Search code examples
javajsonscalajacksonfasterxml

Serlaize case class with the variable inside it in scala with jackson


i am tiring to serialize a case class using jackson fasterxml, i can see the constructor parameters after deserialize (taskRequest and taskNameIn) but not the variables inside the class (jobsRequests is null for example):

//@JsonIgnoreProperties(ignoreUnknown = true) // tried to remove it with no luck
@JsonAutoDetect
case class Job(taskRequest: List[TaskRequest] = Nil,taskNameIn:String) {
{
this.jobsRequests = taskRequest
    this.taskName= taskNameIn
}
@JsonProperty
@volatile private var jobsRequests: List[TaskRequest] = Nil 

@JsonProperty
var task_name: String = ""

}

Any suggestions ?


Solution

  • So there where some problems with the serialization, some where easy but i learn something that may help other people with this problem and the understanding of case class in general.

    First, i used javap(.exe) to see the java code from the class files, to Job.scala with contained case class named Job, there are two class files: Job$.class and Job.class.

    Job$.class:

    public final class logic.Queue.Task.Job$ extends scala.runtime.AbstractFunction4<java.lang.Object, java.lang.String,   scala.collection.immutable.List<logic.Job.TaskRequest>, org.Server.Job.TaskContainer, logic.Queue.Task.Job>     implements scala.Serializable {
      public static final logic.Queue.Task.Job$ MODULE$;
      public static {};
      public final java.lang.String toString();
      .
      .
      .
    }
    

    Job.class:

    public class logic.Queue.Task.Job implements scala.Product,scala.Serializable {
      public static org.Server.Job.TaskContainer apply$default$4();
      public static scala.collection.immutable.List<logic.Job.TaskRequest> apply$default$3();
      .
      .
      .
    }
    

    Meaning that the scala case class is an anonymous inner class and when you try to serialize it (and you can since both implements scala.Serializable), i solved it with adding to the signature to:

    @JsonAutoDetect
    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
    @JsonCreator
    case class Job(stat: Int = CmsTypeMsg.Pending, jobName: String = "", taskRequestIn: List[TaskRequest] = Nil, taskIn: TaskContainer = new TaskContainer()) 
    

    For more help on this issue: http://www.jpalomaki.fi/?p=527 Json deserialization into another class hierarchy using Jackson