【问题标题】:Custom Encoder/Decoder to parse MongoDB Extended JSON自定义编码器/解码器来解析 MongoDB 扩展 JSON
【发布时间】:2017-01-08 02:55:30
【问题描述】:

我正在尝试使用 Circe JSON Parser 解析 MongoDB 扩展 JSON,在大多数情况下都可以正常工作,但特殊数据类型除外,例如。在下面的案例类中,我有priorityOrder,它是长数据类型。

case class relinfo(id:String,assetId:String,insureeId:String,queue:String,priorityOrder:Long) extends baseDomain

但是当它转换为MongoDB JSON格式时,它会转换为下面描述的特殊mongo格式(检查priorityOrder字段)

{
  "_id" : "4abf009d-64b1-496c-b0e8-9061f5e183a0",
  "id" : "4abf009d-64b1-496c-b0e8-9061f5e183a0",
  "assetId" : "e26d5310-ab0c-4672-9971-4babd3420302",
  "insureeId" : "cdee05a1-a09c-4e10-81df-c3f112298cc3",
  "queue" : "Low",
  "priorityOrder" : {
    "$numberLong" : "1930926795621"
  }
}

挑战在于反序列化过程中,如果我尝试获取此 JSON 并使用 circe 解析器转换回具体对象类型,那么它无法映射 priorityOrder 属性,有什么方法可以编写自定义编码器/解码器以特殊方式处理长数据类型。自定义编码器/解码器将从“$numberLong”嵌套类型中读取值并将该值转换为 Long 数据类型。

我从 circe 解析器得到这个异常

Left(DecodingFailure(Long, List(El(DownField(priorityOrder),true,false))))

【问题讨论】:

    标签: mongodb scala circe


    【解决方案1】:

    我能够通过为长数据类型创建自定义解码器来解决这个问题。这是类似船的个人的代码

      implicit val decodeLong: Decoder[Long] = new Decoder[Long] {
          final def apply(c: HCursor): Decoder.Result[Long] = 
            {
              val longval = c.downField("$numberLong").as[String] match 
              {
                case Right(x) => x.toLong
                case _ => throw new Exception("Unable to find $numberLong")
              }
              Right(longval)  
            }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多