【问题标题】:Different Json based on the type of the variable基于变量类型的不同Json
【发布时间】:2018-08-21 07:54:47
【问题描述】:

我有:

case class A(a: T, b: String)

并且我想要基于A类的变量a的不同类型的不同json。

例如,如果类型是 T1,我想要像 { "aaa": "value", "b":"value"} 这样的 json 如果类型是 T2,我想要像 { "bbb": "value", "b":"value"} 这样的 json。

我正在使用喷雾 json

【问题讨论】:

    标签: json scala spray


    【解决方案1】:

    您必须提供自定义协议:

    implicit object AJsonFormat extends RootJsonFormat[A] {
        def write(foo: A) = JsObject(
          foo.a match {
            case a: T1 => "aaa" -> JString(a)
            case a: T2 => "bbb" -> Jstring(a)
          },
          "b" -> JString(foo.b))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 2018-09-26
      相关资源
      最近更新 更多