Skip to content

[Feature Request] Add option to choose which fields should be added to toJson and fromJson #1244

Closed
@joeldomke

Description

@joeldomke

This is a more structured approach to #1178 I already started with the implementation and have written the necessary tests, but there are still some open questions, which I listed below. Once those are answered, I should be able to finish the implementation of this feature.

Problem

The current implementation does not give a lot of flexibility when it comes to defining which properties should be included in fromJson and toJson.

A property will be included in fromJson if all of the following are true:

  • JsonKey.ignore == false
  • JsonSerializable.createFactory == true
  • The property has a setter and getter

A property will be included in toJson if one of the cases below is true:

  • Case 1:
    • JsonKey.ignore == false
    • JsonSerializable.createToJson == true
    • JsonSerializable.createFactory == true
    • The property has a setter and getter
  • Case 2:
    • JsonKey.ignore == false
    • JsonSerializable.createToJson == true
    • JsonSerializable.createFactory == false
    • The property has a getter

Proposal

Add JsonKey.includeWith, which is of type enum IncludeWith{none, fromJson, toJson, both}. If JsonKey.includeWith is null, we resort to the previously described behavior. Otherwise, the decisions will be made as described below. This way, we ensure backwards compatibility.

A property will be included in fromJson if all of the following are true:

  • JsonKey.includeWith is one of {fromJson, both}
  • JsonSerializable.createFactory == true
  • The property has a setter

A property will be include in toJson if all of the following are true:

  • JsonKey.includeWith is one of {toJson, both}
  • JsonSerializable.createToJson == true
  • The property has a getter

Open Questions

  • Currently, if the field map is generated, it will include all elements that are part of fromJson and toJson. I am not sure what this field map is used for or whether it would be a breaking change, if we just included all properties that are either part of fromJson or toJson.
  • What should be done if both ignore and includeWith are non null?
  • What should be done if both the setter and getter have a JsonKey annotation?
  • What should be done if @JsonKey(includeWith: IncludeWith.toJson) is used on a setter, that has no corresponding getter and vice versa?
  • What should be done if @JsonKey(includeWith: IncludeWith.both) is used on a field that only has a setter or getter?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions