在斯卡拉,我有:
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转换为过滤器。
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
validCameraIds
总是
null
. 我错过了什么?