'Json4s not serializing Java classes
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?
Solution 1:[1]
Json4s is the Json library for Scala. To work with Java objects, it is recommended to directly use Jackson. See this question here
Json4s uses jackson only as a parser, and after parsing, it all works by matching from Json4s AST to Scala objects.
If you want to work with Java collections, you should use Jackson directly
So, we can get the mapper
which is an object of Jackson's ObjectMapper
and use it normally -
import org.json4s.jackson.JsonMethods
println(JsonMethods.mapper.writeValueAsString(new Blah("helloooo!!!!")))
Solution 2:[2]
Try to add getter method for your what
property
Solution 3:[3]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SKumar |
Solution 2 | Michael Gantman |
Solution 3 | Moritz |