From 1c1b3cbb30bc54f1f975f3afd924d6d023252a0f Mon Sep 17 00:00:00 2001 From: Performant Data Date: Sun, 23 Jul 2017 00:44:18 -0700 Subject: document how unboxed classes should be handled --- README.markdown | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'README.markdown') diff --git a/README.markdown b/README.markdown index e659e71..a8a7d9d 100644 --- a/README.markdown +++ b/README.markdown @@ -219,6 +219,38 @@ object MyJsonProtocol extends DefaultJsonProtocol { This is a bit more verbose in its definition and the resulting JSON but transports the field semantics over to the JSON side. Note that this is the approach _spray-json_ uses for case classes. +### Providing JsonFormats for unboxed types + +A value class + +```scala +case class PhoneNumber(value: String) extends AnyVal +val num = PhoneNumber("+1 212 555 1111") +``` + +or a class with multiple members + +```scala +case class Money(currency: String, amount: BigDecimal) +val bal = Money("USD", 100) +``` + +can be handled as above with `jsonFormatX`, etc. +It may be preferable, however, to serialize such instances without object boxing: +as `"USD 100"` instead of `{"currency":"USD","amount":100}`. +This requires + +```scala +implicit object MoneyFormat extends JsonFormat[Money] { + val fmt = """([A-Z]{3}) ([0-9.]+)""".r + def write(m: Money) = JsString(s"${m.currency} ${m.amount}") + def read(json: JsValue) = json match { + case JsString(fmt(c, a)) => Money(c, BigDecimal(a)) + case _ => deserializationError("String expected") + } +} +``` + ### JsonFormat vs. RootJsonFormat -- cgit v1.2.3 From 2fbee3fd1c1e44d0182cbb9f5a90d04b07f930e5 Mon Sep 17 00:00:00 2001 From: Performant Data Date: Sun, 23 Jul 2017 00:48:29 -0700 Subject: document how unboxed classes should be handled --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'README.markdown') diff --git a/README.markdown b/README.markdown index a8a7d9d..04eec14 100644 --- a/README.markdown +++ b/README.markdown @@ -238,7 +238,7 @@ val bal = Money("USD", 100) can be handled as above with `jsonFormatX`, etc. It may be preferable, however, to serialize such instances without object boxing: as `"USD 100"` instead of `{"currency":"USD","amount":100}`. -This requires +This requires explicit (de)serialization logic: ```scala implicit object MoneyFormat extends JsonFormat[Money] { -- cgit v1.2.3