我从不同的地方收到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]],
))
}
在我的项目中,我有一个格式化程序特征,我把所有的类格式化程序都放在这个特征中。
当我需要序列化某些东西时,我会使用格式化程序特征扩展类。
我的问题是,我想为同一个类,在相同的特征中制作几个格式化程序 - 然后指定我在实例化我的类时要使用的格式化程序名称。我假设它是这样的:
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]
可能吗?
是的,你可以。首先,如果您希望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