play-json-derived-codecs icon indicating copy to clipboard operation
play-json-derived-codecs copied to clipboard

Excluding type tag from json

Open arshadalis opened this issue 4 years ago • 4 comments
trafficstars

Is there a way to exclude the discriminator type tag from the output json. For example

sealed trait Foo
case class Bar(s :String, w: Long) extends Foo
case class Baz(q : String, p: Int) extends Foo

the output json should be lets say for Bar

{
"s": "someabc"
"w": 12
}

i.e. It should not include "_type": "Bar" in the json.

I found following are the ways to customise the type tag

TypeTagSetting.ShortClassName
TypeTagSetting.FullClassName
TypeTagSetting.UserDefinedName

Is there a way to disable it ?

arshadalis avatar Feb 23 '21 12:02 arshadalis

How would you deserialize such JSON blobs? I mean, how would you detect which concrete class, Bar or Baz you should construct?

julienrf avatar Feb 25 '21 19:02 julienrf

One way to disable it is to have distinct formats, one format for Bar, and one format for Baz (but no format for Foo)

julienrf avatar Feb 25 '21 19:02 julienrf

I can relate to this issue. You could have another TypeTagOWrites function, e.g.

    def default(): TypeTagOWrites =
      new TypeTagOWrites {
        def owrites[A](typeName: String, owrites: OWrites[A]): OWrites[A] =
          OWrites[A](a => owrites.writes(a))
      }

In my case, I want to have all my case classes with different parameters written with one implicit. I do not want to have multiple implicits. However, I want to also add other fields from my sealed trait. I want that to be done in a specific order and different than provided with the "flat" implicit.

I want other fields between my "typeName" and the owrites.writes(a)).

I tested it locally and it works. I can provide the code.

vangogiel avatar Jul 08 '23 12:07 vangogiel

Unless there is a different solution provided with your library that I am unable to see.

vangogiel avatar Jul 08 '23 12:07 vangogiel