Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

json - Json4s ignoring None fields during seriallization (instead of using 'null')

I am having a generic json serialization method that uses json4s. Unfortunately, it is ignoring fields if the value is None. My goal is to have None fields be represented with a null value. I tried by adding custom serializer for None, but still it is not working.

object test extends App {
          class NoneSerializer extends CustomSerializer[Option[_]](format => (
            {     
              case JNull => None
            },
            {
              case None => JNull

            }))

         implicit val f = DefaultFormats + new NoneSerializer

          case class JsonTest(x: String, y: Option[String], z: Option[Int], a: Option[Double], b: Option[Boolean], c:Option[Date], d: Option[Any])

          val v = JsonTest("test", None, None,None,None,None,None); 
println(Serialization.write(v))
}

Result from the above code :

{"x":"test"}

I tried this link and some others, but is is not solving the issue for case classes

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume that you would like to have Nones serialized to null within your JSON. In this case it is sufficient to use DefaultFormats.preservingEmptyValues:

import java.util.Date
import org.json4s._
import org.json4s.jackson.Serialization

object test extends App {

  implicit val f = DefaultFormats.preservingEmptyValues // requires version>=3.2.11

  case class JsonTest(x: String, y: Option[String], z: Option[Int], a: Option[Double], b: Option[Boolean], c:Option[Date], d: Option[Any])

  val v = JsonTest("test", None, None, None, None, None, None);

  // prints {"x":"test","y":null,"z":null,"a":null,"b":null,"c":null,"d":null}
  println(Serialization.write(v))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...