代码之家  ›  专栏  ›  技术社区  ›  ilansch

为同一特性中的同一类定义不同的格式化程序

  •  1
  • ilansch  · 技术社区  · 12 年前

    我从不同的地方接收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]],
    
        ))
        }
    

    在我的项目中,我有一个格式化器特性,我将所有类格式化器都放在这个特性中。
    当我需要序列化一些东西时,我用Formatters特性扩展了类。

    我的问题是,我想为同一个类以相同的特性制作几个格式化程序,然后指定实例化类时要使用的格式化程序名称。 我想应该是这样的:

    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 回复  |  直到 12 年前
        1
  •  3
  •   serejja    12 年前

    是的,你可以。首先,如果你想 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