amnaredo / test

0 stars 0 forks source link

Writer skips fields of case class if they have default value and none was provided #281

Open amnaredo opened 2 years ago

amnaredo commented 2 years ago

Hello,

I have a case class:

case class Been(id: Int, name: String = "sample")

When I start export to json:

implicit val beenRW: ReadWriter[Been] = macroRW[Been]
val b1 = Been(1) // please note that for second field the default is used
println(write(b1, 2))

I get the following output:

{
  "id": 1
}

As you can see the other field (name) was skipped.

How to force it to produce all of the fields regardless whether the default value was used to instantiate the given field or the concreate value was provided during initialization? ID: 343 Original Author: tmichniewski

amnaredo commented 2 years ago

You know when you usually import upickle.default._ – that's object default extends AttributeTagged.

Instead of using the default bundle, you can do:

object SerializeDefaults extends upickle.AttributeTagged{
  override def serializeDefaults = true
}

and then:

implicit val fooDefaultRW: SerializeDefaults.ReadWriter[Been] = SerializeDefaults.macroRW

I haven't done this myself but I would guess that you would generally want to use your new SerializeDefaults bundle instead of upickle.default across your codebase, otherwise you'll be dealing with two bundles and I don't know if that's a good idea.

I see the docs haven't been updated for this new(-ish) feature. If this works for you as expected, please let me know, I can send a PR to update the docs. Original Author: raquo

amnaredo commented 2 years ago

Hello,

I confirm that this solves the issue.

However I think that a better approach would be to alter:

trait MacrosCommon {
  def serializeDefaults: Boolean = false

to change this to true.

If someone export some object to json, then the most natural expectation is to have all the fields exported regardles of how they were initialized. Of course - in my opinion.

Best wishes, Tomek Original Author: tmichniewski

amnaredo commented 2 years ago

BTW - you can close this ticket. Thanks for the support. Original Author: tmichniewski