From 8297c7ae6f1a46df5887e7f3f1d23566b4bd1163 Mon Sep 17 00:00:00 2001 From: Mathias Date: Wed, 25 May 2011 16:32:22 +0200 Subject: Add helper function constructing a jsonFormat from Readers and Writer, implicit conversions from functions --- src/main/scala/cc/spray/json/AdditionalFormats.scala | 16 +++------------- src/main/scala/cc/spray/json/JsonFormat.scala | 12 ++++++++++++ 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/main/scala/cc/spray/json/AdditionalFormats.scala b/src/main/scala/cc/spray/json/AdditionalFormats.scala index 5417e5a..96be8d2 100644 --- a/src/main/scala/cc/spray/json/AdditionalFormats.scala +++ b/src/main/scala/cc/spray/json/AdditionalFormats.scala @@ -27,19 +27,9 @@ trait AdditionalFormats { def read(value: JsValue) = value } - class DelegatingFormat[T](delegate: JsonFormat[T]) extends JsonFormat[T] { - def write(obj: T) = delegate.write(obj) - def read(json: JsValue) = delegate.read(json) - } - - def formatFromWriter[T :JsonWriter] = new JsonFormat[T] { - def write(obj: T) = obj.toJson - def read(value: JsValue) = throw new RuntimeException("JsonFormat constructed from JsonWriter can't read from JSON") - } - - def formatFromReader[T :JsonReader] = new JsonFormat[T] { - def write(obj: T) = throw new RuntimeException("JsonFormat constructed from JsonReader can't write JSON") - def read(value: JsValue) = value.fromJson[T] + def jsonFormat[T](reader: JsonReader[T], writer: JsonWriter[T]) = new JsonFormat[T] { + def write(obj: T) = writer.write(obj) + def read(json: JsValue) = reader.read(json) } /** diff --git a/src/main/scala/cc/spray/json/JsonFormat.scala b/src/main/scala/cc/spray/json/JsonFormat.scala index 94a2576..0fedd3f 100644 --- a/src/main/scala/cc/spray/json/JsonFormat.scala +++ b/src/main/scala/cc/spray/json/JsonFormat.scala @@ -24,6 +24,12 @@ trait JsonReader[T] { def read(json: JsValue): T } +object JsonReader { + implicit def func2Reader[T](f: JsValue => T): JsonReader[T] = new JsonReader[T] { + def read(json: JsValue) = f(json) + } +} + /** * Provides the JSON serialization for type T. */ @@ -31,6 +37,12 @@ trait JsonWriter[T] { def write(obj: T): JsValue } +object JsonWriter { + implicit def func2Writer[T](f: T => JsValue): JsonWriter[T] = new JsonWriter[T] { + def write(obj: T) = f(obj) + } +} + /** * Provides the JSON deserialization and serialization for type T. */ -- cgit v1.2.3