2016-09-21 6 views
0

Generics에서 RootJsonFormat은 어떻게 사용합니까?일반 JSON 지원

trait IDJsonSupport 
    extends SprayJsonSupport 
    with DefaultJsonProtocol{ 

    implicit object AddressIDFormat extends RootJsonFormat[ID[Address]] { 
    override def write(obj: ID[Address]): JsValue = JsNumber(obj.value) 
    override def read(json: JsValue): ID[Address] = json match { 
     case JsNumber(id) => new ID[Address](id.toLongExact) 
     case _ => deserializationError("Address ID expected") 
    } 
    } 

    implicit object CompanyIDFormat extends RootJsonFormat[ID[Company]] { 
    override def write(obj: ID[Company]): JsValue = JsNumber(obj.value) 
    override def read(json: JsValue): ID[Company] = json match { 
     case JsNumber(id) => new ID[Company](id.toLongExact) 
     case _ => deserializationError("Company ID expected") 
    } 
    } 

    implicit object NoteIDFormat extends RootJsonFormat[ID[Note]] { 
    override def write(obj: ID[Note]): JsValue = JsNumber(obj.value) 
    override def read(json: JsValue): ID[Note] = json match { 
     case JsNumber(id) => new ID[Note](id.toLongExact) 
     case _ => deserializationError("Note ID expected") 
    } 
    } 

    ... 

:

내가 복사 붙여 넣기 이런 모든 가능성이 있습니까?

이 :

implicit object AnyIDFormat extends RootJsonFormat[ID[_]] { ... } 

이 작동하지 않습니다.

답변

0

첫째, 나는 ID 클래스는 다음과 같이 정의 가정 : 그렇다면

case class ID[T](value: Long) 

, 당신은 일반적인 형식 implicit def을 정의 할 수 있습니다 특정 형식이 자동으로 스칼라 컴파일러에 의해 생성됩니다.

implicit def genericIDFormat[T]: RootJsonFormat[ID[T]] = new RootJsonFormat[ID[T]] { 
    override def write(obj: ID[T]): JsValue = JsNumber(obj.value) 
    override def read(json: JsValue): ID[T] = json match { 
    case JsNumber(id) => ID(id.toLongExact) 
    case _ => deserializationError("ID expected") 
    } 
} 
+0

감사합니다. TypeTag를 추가해야만했습니다. – Etam