在Scala中,我有:
object CameraIds extends Enumeration {
type CameraIds = Value
val LB, LF, FC, RF, RB, L, F, R, B = Value
def fromString(s: String): Option[Value] = values.find(
_.toString.toLowerCase() == s.toLowerCase())
}
case class Filter(validCameraIds: List[CameraIds])
然后我有一个类型适配器,可用于将Json转换为Filter。
def getListOfCameraIdsTypeAdapter: TypeAdapter[List[CameraIds]] = {
new TypeAdapter[List[CameraIds]] {
override def write(out: JsonWriter, value: List[CameraIds]):
Unit = {
val gson: Gson = new Gson()
val array: JsonWriter = out.beginArray()
value.foreach(camId => array.value(camId.toString))
out.endArray()
}
override def read(in: JsonReader): List[CameraIds] = {
val cameraIds: mutable.Builder[Option[CameraIds],
List[Option[CameraIds]]] = List.newBuilder[Option[CameraIds]]
in.beginArray()
while (in.hasNext) {
val nextCamId = in.nextString()
cameraIds += CameraIds.fromString(nextCamId)
}
in.endArray()
cameraIdsRet.map(_.get)
}
}
}
然后我使用Gson反序列化以下内容:
{
"cameraIds": ["FC", "LB", "RF"]
}
使用以下内容:
val gson: Gson = new GsonBuilder()
.registerTypeAdapter(new TypeToken[List[CameraIds]]() {}.getType,
getListOfCameraIdsTypeAdapter)
.create()
val reader: JsonReader = new JsonReader(
new FileReader(configFilePath.toString));
gson.fromJson(reader, classOf[Filter]);
但是,永远不会调用类型适配器的read
方法,而Filter
的{{1}}总是validCameraIds
。我在这里想念什么?
答案 0 :(得分:0)
问题在于,Slider
的案例类变量名称与validCameraIds
的Json字符串键中的名称不同。显然,Gson在解析之前会查看case类变量名称。