diff options
author | Konrad `ktoso` Malawski <ktoso@project13.pl> | 2017-10-24 14:13:46 +0900 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-10-24 14:13:46 +0900 |
commit | ea6daec0f5d4923048e60c767acc78a6861cf0be (patch) | |
tree | 7a55eba395df075d3c0850c83dfb1d2b44a03fec /README.markdown | |
parent | 36959ef06fa632945ff01aaa2cc558b6cc8365d7 (diff) | |
parent | 2fbee3fd1c1e44d0182cbb9f5a90d04b07f930e5 (diff) | |
download | spray-json-ea6daec0f5d4923048e60c767acc78a6861cf0be.tar.gz spray-json-ea6daec0f5d4923048e60c767acc78a6861cf0be.tar.bz2 spray-json-ea6daec0f5d4923048e60c767acc78a6861cf0be.zip |
Merge pull request #235 from performantdata/master
document how unboxed classes should be handled
Diffstat (limited to 'README.markdown')
-rw-r--r-- | README.markdown | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/README.markdown b/README.markdown index b62918e..30ca8ed 100644 --- a/README.markdown +++ b/README.markdown @@ -220,6 +220,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 explicit (de)serialization logic: + +```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 |