【问题标题】:Circe trait fields not included in jsonCirce 特征字段不包含在 json 中
【发布时间】:2017-03-31 16:27:44
【问题描述】:

我有一个简单的特征,它在某些案例类中混杂在一起。当通过 circe 将该类的实例转换为 JSON 时,我意识到 trait 中具有默认值的字段不包含在 JSON 字符串中。

我使用io.circe.generic.auto._ 进行编码

举例说明:

  trait Base {
    var timestamp: Timestamp = new Timestamp(System.currentTimeMillis())
    var version = 0
  }

  case class CC(id: String) extends Base

  val cc = CC("testId")
  val str = cc.asJson.noSpaces

给出:{"id":"testId"}

所以str 不包含我期望的时间戳和版本值

我假设它使用编码器进行案例类并且只是跳过一个特征。我还需要做什么才能包含这些字段?

在不同版本的 circe(0.3.0 和 0.6.0)中试过这个

我也可以稍后从 JSON 字符串中解码这些字段(可以有其他值),还是我应该更好地保留这些字段抽象并在案例类中使用默认参数?

【问题讨论】:

    标签: json scala traits circe


    【解决方案1】:

    您需要将这些字段直接添加到 CC 案例类中,或明确定义您自己的编码器。

    我会这样做:

      trait Base {
        def timestamp: Timestamp
        def version: Int
      }
    
      case class CC(id: String, timestamp: Timestamp, version: Int) 
        extends Base
    
      object CC {
        def apply(id: String) = new CC(
          id, new Timestamp(System.currentTimeMillis()), 0
        )
      }
    
      val cc = CC("testId")
      val str = cc.asJson.noSpaces
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 2018-05-18
      • 2019-01-07
      • 2017-04-24
      • 2019-09-18
      相关资源
      最近更新 更多