在将对象/ 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"}
答案 0 :(得分:3)
case class Book(title: Option[String], author: String)
val b = Book(None, "Arthur C. Clark")
println(write(b))
res1:> {"author":"Arthur C. Clark"}
您可以使用Option
来定义变量。如果不是,则不会序列化此变量。
还有另一种方法可以在removeField
decompose
object
之后使用bookJValue.removeFile {
case (_, JNull) => true
case _ => false
}
来执行此操作,例如:
# LOGGING
logging.path=/var/log
logging.file=myapp.log
答案 1 :(得分:1)
您可以轻松创建自己的自定义序列化程序。跟我来。
首先在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 project页面上找到更多信息。