正如标题已经说明的那样,我想反序列化包含以@@开头的密钥的json字符串。使用@@时,使用案例类的标准方法令人遗憾地不再起作用。
val test = """{"@@key": "value"}"""
case class Test(@@key: String) // not possible
val gson = new GsonBuilder().create()
val res = gson.fromJson(test, classOf[Test])
如何使用@@而不预处理输入的json字符串?
最简单的答案是引用字段名称:
case class Test(`@@key`: String)
我做了一些实验,但似乎GSON与Scalacase class
es的互操作性不好(或者反之,我想这只是一个透视问题)。我尝试使用scala.beans.BeanProperty
,但似乎没有什么不同。
一种可行的方法是使用常规的class
和SerializedName
注释,如本例所示:
import com.google.gson.{FieldNamingPolicy, GsonBuilder}
import com.google.gson.annotations.SerializedName
final class Test(k: String) {
@SerializedName("@@key") val key = k
override def toString(): String = s"Test($key)"
}
val test = """{"@@key": "foobar"}"""
val gson = new GsonBuilder().create()
val res = gson.fromJson(test, classOf[Test])
println(res)
您可以尝试使用此代码here on Scastie.
您可以阅读有关SerializedName
(以及其他与命名相关的GSON功能)here on the user guide的更多信息。