在同一特征中为同一个类定义不同的格式化程序

时间:2014-04-02 12:57:49

标签: json scala

我从不同的地方收到json字符串,我希望构建相同的类实例,问题是来自地方A我得到一些字段,当我从地方B得到json时,我得到相同的字段和更多。

我知道json解析有两种方法:

//Option 1 - Serialize all the fields, if a field is not found on json, it throws exception
implicit val myClassFormat = Json.format[MyClass] //This will format all fields

//Option 2 - Serialize only the fields i want
implicit val myClassFormatCustom = new Format[MyClass]{
def writes(item: MyClass):JsValue = {
  Json.obj(
      "field1" -> item.field1,
      "field2" -> item.field2
      )
}
def reads(json: JsValue): JsResult[MyClass] = 
JsSuccess(new MyClass(
    (json \ "field1").as[Option[String]],
    (json \ "field2").as[Option[String]],

    ))
    }

在我的项目中,我有一个Formatter特征,我将所有类格式化程序放在这个特性中 当我需要序列化某些内容时,我使用Formatters trait扩展了类。

我的问题是,我想在相同的特性中为同一个类制作几个Formatter - 然后指定我想在实例化我的类时使用的格式化名称。 我认为它类似于:

val myclass:MyClass = Json.parse(someString).as[MyClass] //This is current and not good !
val myclass:MyClass = Json.parse(someString, myClassFormatCustom /*the formatter name*/).as[MyClass]

有可能吗?

1 个答案:

答案 0 :(得分:3)

是的,你可以。首先,如果您希望myClassFormat成为默认格式 - 它必须是唯一的隐式格式(即使myClassFormatCustom不隐式)。

然后你就可以这样做:

val myclass:MyClass = Json.parse(someString).as[MyClass] //default case - uses the implicit format

val mc2 = Json.parse(someString).as(myClassFormatCustom) //custom case - uses the provided Reads or Format