Pure Config枚举配置解析问题:大小写混合值触发转换失败
PureConfig大小写混合枚举值解析失败的解决方案
问题核心:默认情况下,PureConfig的FieldCoproductHint会将密封特质的case object名称转为小写作为匹配键(比如Student对应"student"),当配置中传入大小写混合的值(如"StudenT")时,无法匹配到对应的case object,触发ConvertFailure错误。
解决方法:自定义忽略大小写的CoproductHint
通过自定义FieldCoproductHint,将输入的配置值转为小写(或直接忽略大小写比较),实现不区分大小写的解析。
修改后的完整代码:
import pureconfig._ import pureconfig.generic.FieldCoproductHint import pureconfig.generic.semiauto._ sealed trait Occupation extends Product with Serializable object Occupation { // 自定义忽略大小写的CoproductHint,指定type字段作为判别键 private case object CaseInsensitiveFieldHint extends FieldCoproductHint[Occupation]("type") { override def decode(name: String): Option[String] = Some(name.toLowerCase) // 将输入值转为小写,匹配case object的默认小写键 } case class Employed(job: String) extends Occupation object Employed { implicit val employedReader = deriveReader[Employed] } case object Unemployed extends Occupation case object Student extends Occupation // 使用自定义Hint生成Occupation的Reader implicit val occupationReader = deriveReader[Occupation](CaseInsensitiveFieldHint) } case class WorkingPerson(name: String, surname: String, occupation: Occupation) // 测试大小写混合的配置值 val res = ConfigSource.string("{ name: Isaac, surname: Newton, occupation.type: StudenT }").load[WorkingPerson] // 此时res会成功解析,occupation为Occupation.Student
原理说明
- 默认的
FieldCoproductHint会将case object的名称转为小写(如Student→"student"),并严格匹配配置中的type字段值。 - 自定义的
CaseInsensitiveFieldHint重写了decode方法,把输入的type值统一转为小写,这样无论输入是全大写、全小写还是混合大小写,都能匹配到对应的case object键。
如果需要更严格的忽略大小写匹配(比如避免不同case object转小写后重名的情况),也可以改成直接匹配可能的枚举值:
private case object CaseInsensitiveFieldHint extends FieldCoproductHint[Occupation]("type") { override def decode(name: String): Option[String] = possibleValues.find(_.equalsIgnoreCase(name)) }
内容的提问来源于stack exchange,提问作者Arlengur
相关产品推荐
相关产品推荐

