[英]Json4s not serializing Java classes
I have some scala code that needs to be able to serialize/deserialize some Java classes using Json4s.我有一些 scala 代码需要能够使用 Json4s 序列化/反序列化一些 Java 类。
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.我正在使用
"org.json4s" %% "json4s-ext" % "4.0.5"
和"org.json4s" %% "json4s-jackson" % "4.0.5"
尽管我也尝试过3.6.7
版本。
Model Code (Java): Model 代码(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):序列化(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.我知道我可以为每个 Java class 编写一个
CustomSerializer
,但我有很多 Java 类,我真的很想避免这样做。 Any ideas on how to make this work?关于如何使这项工作有任何想法吗?
Json4s is the Json library for Scala. To work with Java objects, it is recommended to directly use Jackson. See this question here Json4s 是 Scala 的 Json 库。要使用 Java 对象,建议直接使用 Jackson。请看这里这个问题
Json4s uses jackson only as a parser, and after parsing, it all works by matching from Json4s AST to Scala objects.
Json4s 只使用 jackson 作为解析器,解析后都是通过从 Json4s AST 匹配到 Scala 对象来工作的。
If you want to work with Java collections, you should use Jackson directly
如果你想使用 Java collections,你应该直接使用 Jackson
So, we can get the mapper
which is an object of Jackson's ObjectMapper
and use it normally -因此,我们可以获得
mapper
,它是 Jackson 的ObjectMapper
的 object 并正常使用它 -
import org.json4s.jackson.JsonMethods
println(JsonMethods.mapper.writeValueAsString(new Blah("helloooo!!!!")))
Try to add getter method for your what
property尝试为您的
what
属性添加 getter 方法
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: Json4s 忽略任何
JsonProperty
注释,并且需要一个构造函数参数和一个 Scala 案例类样式的 getter 方法,用于 Java model class 的每个属性。在上面的示例中,它看起来像:
public class Blah {
private final String what;
public String what() {
return what;
}
public Blah() {
this(null);
}
public Blah(String what) {
this.what = what;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.