我在序列化使用CharSequence而不是String的类时遇到问题。当我使用Strings时,一切正常。
我有以下课程:
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()?
答案 0 :(得分: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)