将枚举字段序列化为BSON的异常

问题描述 投票:0回答:1

我正在使用PlayFramework 2.6与SCALA和mongodb-driver。

在写入时挣扎着使用Eumeration序列化。

当我尝试插入包含枚举字段的对象时,我得到异常:

Caused by: org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class scala.Enumeration$Val.
at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37)
at org.mongodb.scala.bson.codecs.macrocodecs.MacroCodec.writeValue(MacroCodec.scala:167)
at org.mongodb.scala.bson.codecs.macrocodecs.MacroCodec.writeValue$(MacroCodec.scala:162)

我为对象本身创建了编解码器,也试图为枚举类类型创建编解码器,但看起来它是正确的方式。

  val routeTypeCodec: CodecProvider = Macros.createCodecProvider[RouteTypeClass]
  val routeCodec: CodecProvider = Macros.createCodecProviderIgnoreNone[Route]

列举:

class RouteTypeClass extends TypeReference[RouteType.type]

object RouteType extends Enumeration {
  type RouteType = Value
  val Repeat, OneTime = Value
}

保存对象:

case class Route(
 ...
 routeType: RouteType
 ...
);

如何为枚举字段编写编解码器,除了将此字段定义为String。

mongodb scala serialization playframework
1个回答
0
投票

放弃使用枚举。相反,使用密封的特征和案例类。不是太优雅的解决方案,但有效。

sealed trait RouteType {
  def routeType: String
}

case class Repeat() extends RouteType {
  override val routeType: String = "Repeat"
}
case class OneTime() extends RouteType {
  override val routeType: String = "OneTime"
}

objet RouteType {
  def parseFromString(value: String): Option[RouteType] = {
    Vector(Repeat(), OneTime().find(_.routeType == value)
  }
}

并为这些编写自定义BSON编解码器

import org.bson.{BsonReader, BsonWriter}
import org.bson.codecs.{Codec, DecoderContext, EncoderContext}

class RouteTypeCodec extends Codec[RouteType] {
  override def encode(
    writer: BsonWriter,
    value: RouteType,
    encoderContext: EncoderContext
  ): Unit = writer.writeString(value.routeType)
  override def getEncoderClass: Class[RouteType] = classOf[RouteType]
  override def decode(reader: BsonReader,
                        decoderContext: DecoderContext): RouteType= {
    val value = reader.readString()
    val result = RouteType.parseFromString(value)
    if (result.isDefined) result.get else throw new IllegalArgumentException("No such RouteType")
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.