【问题标题】:Json.asString returns None even though Json.toString returns the correct valueJson.asString 返回 None 即使 Json.toString 返回正确的值
【发布时间】:2019-07-09 08:41:12
【问题描述】:

给定以下案例类LogMessage

import io.circe.{Decoder, Encoder}
import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
import enumeratum.{CirceEnum, Enum, EnumEntry}
import io.circe.syntax._

sealed trait LogLevel extends EnumEntry

object LogLevel extends Enum[LogLevel] with CirceEnum[LogLevel] {
  val values = findValues

  case object Warning extends LogLevel
  case object Error   extends LogLevel
  case object Info    extends LogLevel
  case object Success extends LogLevel
}

object LogMessage {
  implicit val logMessageDecoder: Decoder[LogMessage] = deriveDecoder[LogMessage]
  implicit val logMessageEncoder: Encoder[LogMessage] = deriveEncoder[LogMessage]
}

case class LogMessage(level: LogLevel, text: String, args: List[String], date: Long)
case class MyClass[A](obj: A)(implicit encoder: Encoder[A]) {
    def message1: String = obj.asJson.toString
    def message2: Option[String] = obj.asJson.asString
}

为什么会这样:

val x = MyClass(LogMessage(LogLevel.Info, "test notification", Nil, 1550218866571))

x.message1 // {\n  "level" : "Info",\n  "text" : "test notification",\n  "args" : [\n  ],\n  "date" : 1550218866571\n}

但这不是:

x.message2 // None

这里是解决此问题的 Scastie 的链接:link

【问题讨论】:

    标签: json scala circe


    【解决方案1】:

    大约Json 有六个asX 方法,对应于JSON 中的六种数据类型。例如,如果 Json 实例 x 表示 JSON 布尔值,x.asBoolean 将返回包含值作为 BooleanSome,但如果 x 是 JSON 字符串、数组、对象、数字, 或 null,x.asBoolean 将为空。

    在这种情况下,您会看到 .asString 返回 None,因为您在代表 JSON 对象而不是 JSON 字符串的 Json 值上调用它。

    Json 上的 toString 方法完全不同:它是通用的 Scala / Java toString,在 Json 的情况下实现为 .spaces2。我不确定您要在这里做什么,但总的来说,我建议避免使用 toString — 如果您想序列化 io.circe.Json 值,最好使用打印机或制作更明确的格式化选项(例如noSpacesspaces2 等)。

    (对于它的价值,我对asStringasNull 等方法在Json 上的命名并不完全满意。通常,在方法名称中使用“as”进行编码或解码,这并不完全是在这些情况下发生的事情,但它已经足够接近了,我从来没有费心想出更好的选择。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多