为同一特征中的同一类定义不同的格式化程序 [英] Define different formatters for same class in the same trait
问题描述
我从不同的地方收到json字符串,我希望构造相同的类实例,问题是从A地方我得到了一些字段,而当我从B地方得到json时,我得到了相同的字段等等.
I receive json string from different places, I wish to construct the same class instance, the problem is the from place A i get some fields, and when i get the json from place B, i get the same fields and more.
我知道有两种解析json的方法:
I know there are 2 approaches for json parsing:
//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都置于该特性中.
当我需要序列化某些东西时,我可以扩展具有Formatters特性的类.
In my project, I have a Formatter trait, and i put all the classes formatters in this trait.
When i need to serialize something i extend the class with Formatters trait.
我的问题是,我想为同一类,具有相同特征的多个Formatter创建一个格式化程序,然后指定在实例化我的类时要使用的格式化程序名称. 我认为它类似于:
My question is, I want to make several Formatters for the same class, in the same trait -and then specify the formatter name i would like to use when instantiating my class. I assume it goes something like:
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
不为隐式).
Yes, you can. First, if you want the myClassFormat
to be the default one - it must be the only implicit format (i.e. make the myClassFormatCustom
not implicit).
然后您将可以执行以下操作:
Then you'll be able to do like this:
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
这篇关于为同一特征中的同一类定义不同的格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!