JSON4S不序列化Java课程
我有一些Scala代码,需要能够使用JSON4S序列化/估算一些Java类。
我正在使用“ org.json4s” %%“ json4s-ext”%“ 4.0.5”
和“ org.json4s” %%“ JSON4S-JACKSON”%4.0.5“
我也尝试了3.6.7
版本。
模型代码(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;
}
}
序列化(Scala):
import org.json4s.DefaultFormats
import org.json4s.jackson.Serialization
println(Serialization.write(new Blah("helloooo!!!!"))(DefaultFormats))
它仅打印出:{}
。
我了解我可以为每个Java类编写CustomSerializer
,但是我有很多Java类,并且真的很想避免这样做。关于如何使这项工作的想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
JSON4S是Scala的JSON库。要使用Java对象,建议直接使用Jackson。请参阅此问题在这里
因此,我们可以获得
mapper
,它是杰克逊的objectMapper
的对象,并正常使用它 -Json4s is the Json library for Scala. To work with Java objects, it is recommended to directly use Jackson. See this question here
So, we can get the
mapper
which is an object of Jackson'sObjectMapper
and use it normally -尝试为您的
添加Getter方法
Try to add getter method for your
what
propertyJSON4S忽略任何
JSONPROPERTY
注释,需要为Java模型类的每个属性提供构造函数参数和Scala Case-class样式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: