当将object/JObject转换为json字符串时,如何防止json4s呈现空值?
在杰克逊,你可以这样做:
mapper.setSerializationInclusion(Include.NON_NULL)我如何在json4s中做同样的事情呢?
示例
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import org.json4s.{Extraction, NoTypeHints}
case class Book(title: String, author: String)
implicit val formats = Serialization.formats(NoTypeHints)
val bookJValue = Extraction.decompose(Book(null, "Arthur C. Clark"))
# JObject(List((title,JNull), (author,JString(Arthur C. Clark))))
val compacted = compact(render(bookJValue))
# {"title":null,"author":"Arthur C. Clark"}我想要压缩的json是这样的:
{"author":"Arthur C. Clark"}发布于 2015-10-23 09:18:51
case class Book(title: Option[String], author: String)
val b = Book(None, "Arthur C. Clark")
println(write(b))
res1:> {"author":"Arthur C. Clark"}您可以使用Option定义变量。如果为none,则不会序列化该变量。
还有一种方法可以通过在您的removeField之后使用decompose来实现这一点,比如:
bookJValue.removeFile {
case (_, JNull) => true
case _ => false
}发布于 2015-10-23 15:36:55
您可以轻松地创建您自己的自定义序列化程序。跟我来。
首先,在formats中做一些小的改变
implicit val formats = DefaultFormats + new BookSerializer之后,构建您自己的序列化程序/反序列化程序:
class BookSerializer extends CustomSerializer[Book](format => (
{
case JObject(JField("title", JString(t)) :: JField("author", JString(a)) ::Nil) =>
new Book(t, a)
},
{
case x @ Book(t: String, a: String) =>
JObject(JField("title", JString(t)) ::
JField("author", JString(a)) :: Nil)
case Book(null, a: String) =>
JObject(JField("author", JString(a)) :: Nil) // `title` == null
}
))第一部分是反序列化器(将数据从json转换到case类),第二部分是序列化器(从case类到json的转换)。我增加了title == null的案例。您可以随心所欲地添加更多的案例。
整份清单:
import org.json4s.jackson.JsonMethods._
import org.json4s.{DefaultFormats, Extraction}
import org.json4s._
case class Book(title: String, author: String)
implicit val formats = DefaultFormats + new BookSerializer
class BookSerializer extends CustomSerializer[Book](format => (
{
case JObject(JField("title", JString(t)) :: JField("author", JString(a)) ::Nil) =>
new Book(t, a)
},
{
case x @ Book(t: String, a: String) =>
JObject(JField("title", JString(t)) ::
JField("author", JString(a)) :: Nil)
case Book(null, a: String) =>
JObject(JField("author", JString(a)) :: Nil) // `title` == null
}
))
val bookJValue = Extraction.decompose(Book(null, "Arthur C. Clark"))
val compacted = compact(render(bookJValue))输出:
compacted: String = {"author":"Arthur C. Clark"}您可以在json4s项目的页面上找到其他信息。
https://stackoverflow.com/questions/33297913
复制相似问题