summaryrefslogtreecommitdiff
path: root/README.markdown
diff options
context:
space:
mode:
authorPerformant Data <performantdata@users.noreply.github.com>2017-07-23 00:44:18 -0700
committerGitHub <noreply@github.com>2017-07-23 00:44:18 -0700
commit1c1b3cbb30bc54f1f975f3afd924d6d023252a0f (patch)
treec29ead5fbb21549dbab0d5b9866eab75ef95e745 /README.markdown
parent8a421f066e99359a3d6fa4cd64cded206376d264 (diff)
downloadspray-json-1c1b3cbb30bc54f1f975f3afd924d6d023252a0f.tar.gz
spray-json-1c1b3cbb30bc54f1f975f3afd924d6d023252a0f.tar.bz2
spray-json-1c1b3cbb30bc54f1f975f3afd924d6d023252a0f.zip
document how unboxed classes should be handled
Diffstat (limited to 'README.markdown')
-rw-r--r--README.markdown32
1 files changed, 32 insertions, 0 deletions
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