olon.json.Serialization.scala Maven / Gradle / Ivy
The newest version!
package olon
package json
import izumi.reflect.Tag
/** 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
* olon.json.TypeHints
*/
object Serialization {
import java.io.{Reader, StringWriter, Writer}
/** Serialize to String.
*/
def write[A <: Any](a: A)(implicit formats: Formats): String =
compactRender(Extraction.decompose(a)(formats))
/** Serialize to Writer.
*/
def write[A <: Any, W <: Writer](a: A, out: W)(implicit
formats: Formats
): W = {
JsonAST.compactRender(Extraction.decompose(a)(formats), out)
out
}
/** Serialize to String (pretty format).
*/
def writePretty[A <: Any](a: A)(implicit formats: Formats): String =
(writePretty(a, new StringWriter)(formats)).toString
/** Serialize to Writer (pretty format).
*/
def writePretty[A <: Any, W <: Writer](a: A, out: W)(implicit
formats: Formats
): W = {
JsonAST.prettyRender(Extraction.decompose(a)(formats), out)
out
}
/** Deserialize from a String.
*/
// SCALA3 Using `izumi.reflect.Tag` instead of `Manifest`
def read[A](json: String)(implicit formats: Formats, mf: Tag[A]): A =
parse(json).extract(formats, mf)
/** Deserialize from a Reader.
*/
// SCALA3 Using `izumi.reflect.Tag` instead of `Manifest`
def read[A](in: Reader)(implicit formats: Formats, mf: Tag[A]): A =
JsonParser.parse(in).extract(formats, mf)
/** Create Serialization formats with given type hints. Example:
val
* hints = new ShortTypeHints( ... ) implicit val formats =
* Serialization.formats(hints)
*/
def formats(hints: TypeHints) = new Formats {
val dateFormat = DefaultFormats.lossless.dateFormat
override val typeHints = hints
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy