简体   繁体   中英

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 ?

Jackson uses Getter from the Java Beans standard to construct the json. Try adding @BeanProperty to your properties and constructor parameters to compile your class with Getter/Setters.

Example

Or you could use the Jackson Scala-Module . You can take a look at their tests to see how to use this module for serialization .

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

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