I have some scala code that needs to be able to serialize/deserialize some Java classes using Json4s.
I am using "org.json4s" %% "json4s-ext" % "4.0.5"
and "org.json4s" %% "json4s-jackson" % "4.0.5"
though I have also tried with the 3.6.7
version.
Model Code (Java):
import com.fasterxml.jackson.annotation.JsonProperty;
public class Blah {
@JsonProperty("what")
public final String what;
public Blah() {
this(null);
}
public Blah(String what) {
this.what = what;
}
}
Serialization (Scala):
import org.json4s.DefaultFormats
import org.json4s.jackson.Serialization
println(Serialization.write(new Blah("helloooo!!!!"))(DefaultFormats))
It only ever prints out: {}
.
I understand I can write a CustomSerializer
for each Java class but I have a lot of Java classes and would really like to avoid doing that. Any ideas on how to make this work?
CodePudding user response:
Try to add getter method for your what
property
CodePudding user response:
Json4s ignores any JsonProperty
annotation and requires both a constructor parameter and a Scala case-class style getter method for each property of your Java model class. In the example above that would look like:
public class Blah {
private final String what;
public String what() {
return what;
}
public Blah() {
this(null);
}
public Blah(String what) {
this.what = what;
}
}