我是 Scala 的新手,在这里我试图创建一个基于 Argonaut 的通用 json 转换器。我曾尝试在 google 和 stackoverflow 上进行搜索,但到目前为止我一无所知。
这是我的代码片段。
import org.springframework.http.converter.AbstractHttpMessageConverter
import org.springframework.http.{MediaType, HttpInputMessage, HttpOutputMessage}
import scala.io.Source
import argonaut._,Argonaut._
case class Currency(code: String)
object Currency {
implicit def CurrencyCodecJson: CodecJson[Currency] = casecodec1(Currency.apply, Currency.unapply)("code")
}
case class Person(firstName: String, lastName: String)
object Person {
implicit def PersonCodecJson: CodecJson[Person] = casecodec2(Person.apply, Person.unapply)("firstName", "LastName")
}
class ArgonautConverter extends AbstractHttpMessageConverter[Object](new MediaType("application", "json", Charset.forName("UTF-8")), new MediaType("application", "*+json", Charset.forName("UTF-8"))) {
val c = classOf[Currency]
val p = classOf[Person]
def writeInternal(t: Object, outputStream: OutputStream) = {
val jsonString = t match {
case c:Currency => c.asJson.ToString()
case p:Person => p.asJson.ToString()
}
def supports(clazz: Class[_]): Boolean = clazz.isAssignableFrom(classOf[CodecJson])// clazz == classOf[Currency] || clazz == classOf[LegalEntity]
def readInternal(clazz: Class[_ <: Object], inputStream: InputStream): Object = {
val jsonString = Source.fromInputStream(inputStream).getLines.mkString
val jsonObject = clazz match {
case `c` => jsonString.decodeOption[Currency]
case `p` => jsonString.decodeOption[Person]
}
jsonObject match {
case Some(j) => j
case None => null
}
}
}
我要做的是进行概括,这样我就不需要为将来添加的每个新模型类(如本例中的 Currency 和 Person)继续添加匹配项。