Define different formatters for same class in the

2019-08-12 21:03发布

问题:

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.

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]],

    ))
    }

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.

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]

Is it possible ?

回答1:

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


标签: json scala