1

我在序列化使用 CharSequence 而不是 String 的类时遇到问题。当我使用字符串时,一切正常。

我有以下课程:

case class Word(word: CharSequence,
            meanings: Traversable[CharSequence],
            readings: Traversable[CharSequence]) {
}

当我尝试这样序列化它时:

...
val word = new Word("dog", List("Foo", "Goo"), List("Ba", "Fa"))
implicit val wordWrites = Json.writes[Word]
Ok(Json.toJson(word)).as(JSON)

我收到以下错误:

error: exception during macro expansion:
scala.reflect.macros.TypecheckException: No implicit Writes for CharSequence, Traversable[CharSequence], Traversable[CharSequence] available.
at scala.reflect.macros.runtime.Typers$class.inferImplicit(Typers.scala:55)
at scala.reflect.macros.runtime.Typers$class.inferImplicitValue(Typers.scala:38)
at scala.reflect.macros.runtime.Context.inferImplicitValue(Context.scala:6)
at scala.reflect.macros.runtime.Context.inferImplicitValue(Context.scala:6)
at play.api.libs.json.JsMacroImpl$$anonfun$15.apply(JsMacroImpl.scala:332)
at play.api.libs.json.JsMacroImpl$$anonfun$15.apply(JsMacroImpl.scala:317)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.immutable.List.foreach(List.scala:309)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
at scala.collection.AbstractTraversable.map(Traversable.scala:105)
at play.api.libs.json.JsMacroImpl$.writesImpl(JsMacroImpl.scala:317)
implicit val wordWrites = Json.writes[Word]

我知道序列化框架的作者可能忘记支持 CharSequence。但是,如何给序列化程序一个合理的默认值,以便在所有 CharSequence 实例上调用 .toString() ?

4

1 回答 1

4

您可以定义一个 CharSequence 格式:

implicit var csFormat = new Format[CharSequence] {
  def writes(c: CharSequence): JsValue = Json.toJson(c.toString)
  def reads(jv: JsValue): JsResult[String] = JsSuccess(Json.stringify(jv))
}

val word = new Word("dog", List("Foo", "Goo"), List("Ba", "Fa"))
implicit val wordWrites = Json.format[Word]
Ok(Json.toJson(word)).as(JSON)
于 2013-03-05T08:23:24.323 回答