【问题标题】:Gson toJson escapes fields that are OptionGson toJson 转义 Option 字段
【发布时间】:2020-06-22 22:17:30
【问题描述】:

我有一个这样的案例类:

case class TotalTest(f1: Option[String], f2: Option[String], f3: String)

使用Gson,我正在尝试将内容写入 Json 文件,这是我得到的:


val test1 = (new Gson).toJson(TotalTest(Some("a"), Some("b"), "c"))
val pw1 = new PrintWriter(new File("test1.json" ))
pw1.write(test1)
pw1.close

内容是:

{"f1":{},"f2":{},"f3":"c"}

为什么我会丢失前两个字段?基本上,我有一个高度嵌套的案例类对象,其中包含很多 Options,我想知道一种提取结果的简单方法。

Related question

【问题讨论】:

    标签: json scala gson


    【解决方案1】:

    感谢this answer,我们可以使用Circe

    import io.circe.generic.auto._
    import io.circe.parser._
    import io.circe.syntax._
    
    val totalTest = TotalTest(Some("a"), Some("b"), "c")
    val pw1 = new PrintWriter(new File("test1.json" ))
    pw1.write(totalTest.asJson.noSpaces)
    pw1.close
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多