
org.json4s.jackson.Serialization.scala Maven / Gradle / Ivy
The newest version!
package org.json4s
package jackson
import reflect.Manifest
import com.fasterxml.jackson.databind.DeserializationFeature
/** Functions to serialize and deserialize a case class.
* Custom serializer can be inserted if a class is not a case class.
*
* Example:
* val hints = new ShortTypeHints( ... )
* implicit val formats = Serialization.formats(hints)
*
*
* @see org.json4s.TypeHints
*/
object Serialization extends Serialization {
import java.io.{Reader, StringWriter, Writer}
/** Serialize to String.
*/
def write[A <: AnyRef](a: A)(implicit formats: Formats): String =
(write(a, new StringWriter)(formats)).toString
/** Serialize to Writer.
*/
def write[A <: AnyRef, W <: Writer](a: A, out: W)(implicit formats: Formats): W = {
JsonMethods.mapper.writeValue(out, Extraction.decompose(a)(formats))
out
}
/** Serialize to String (pretty format).
*/
def writePretty[A <: AnyRef](a: A)(implicit formats: Formats): String =
(writePretty(a, new StringWriter)(formats)).toString
/** Serialize to Writer (pretty format).
*/
def writePretty[A <: AnyRef, W <: Writer](a: A, out: W)(implicit formats: Formats): W = {
JsonMethods.mapper.writerWithDefaultPrettyPrinter.writeValue(out, Extraction.decompose(a)(formats))
out
}
/** Deserialize from a String.
*/
def read[A](json: String, useBigDecimalForDouble: Boolean = false)(implicit formats: Formats, mf: Manifest[A]): A =
JsonMethods.parse(json, useBigDecimalForDouble).extract(formats, mf)
/** Deserialize from a Reader.
*/
def read[A](in: Reader, useBigDecimalForDouble: Boolean)(implicit formats: Formats, mf: Manifest[A]): A = {
JsonMethods.mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, useBigDecimalForDouble)
JsonMethods.mapper.readValue[JValue](in, classOf[JValue]).extract(formats, mf)
}
/** Deserialize from a Reader.
*/
def read[A](in: Reader)(implicit formats: Formats, mf: Manifest[A]): A = read[A](in, false)
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy