json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Implement JsonKey - readonly, writeonly

Open bsutton opened this issue 4 years ago • 9 comments

We have a class that contains fields that we need to fetch from the server but we can't send back to the server. As such we want to be able to define a field as being readonly and for symmetries sake we should have the ability to mark a field as write only.

Read only

class Team
{
@JsonKey(readOnly: true)
 List<User> members;
}

The readonly argument would cause the json serializer to suppress the generation of the members field in the toJson function.

Write only

class Team
{
@JsonKey(writeOnly: true)
 List<User> members;
}

The writeOnly argument would cause the json serializer to suppress the generation of the members field in the fromJson function.

bsutton avatar Nov 28 '19 03:11 bsutton

I would be happy to contribute this code but need to see my existing PR through the merge process first (for obvious reasons).

bsutton avatar Nov 28 '19 03:11 bsutton

This is actually a very good idea. We need the exact same thing in our app. Any updates?

guyzk avatar Feb 13 '20 08:02 guyzk

I need exactly the same thing, there is the annotation ignore, I think they could be ignoreDecode and ignoreEncode

FernandoUFS avatar Apr 17 '20 03:04 FernandoUFS

Is there any update on this?

vedantrathore avatar Jul 23 '20 12:07 vedantrathore

I would suggest to reuse existing field's attributes toJson and fromJson - ignore it when set to null. I use following workaround with ignore global function which always returns null and null values are not processed (by includeIfNull: false).

@JsonSerializable(includeIfNull: false)
class Model {
  @JsonKey(fromJson: ignore)
  int writeOnlyNumber;
  @JsonKey(toJson: ignore)
  String readOnlyText;
}

T? ignore<T>(dynamic _) => null;

edlman avatar Mar 24 '21 09:03 edlman

I think this feature would be really helpful without having to implement workarounds like the above everytime.

arafaysaleem avatar Apr 30 '21 10:04 arafaysaleem

Any update on this?

Talgat777 avatar Oct 18 '21 10:10 Talgat777

No update. Pondering the best way to implement this.

I'd like go with – maybe – an enum enum IncludeWith { both, toJson, fromJson, ignore} and default to both.

Then this would take the place of ignore eventually.

kevmoo avatar Oct 27 '21 22:10 kevmoo

@kevmoo any update? or anyone else?

Need this too.

matanshukry avatar Apr 16 '22 19:04 matanshukry

I hope to jump on this NEXT. Not sure when NEXT will be, but hopefully soon!

kevmoo avatar Nov 17 '22 23:11 kevmoo

I have a (draft) PR out on this. I'd LOVE (early) feedback about if this works for what folks need here: https://github.com/google/json_serializable.dart/pull/1256

I still need to do some documentation and testing...

kevmoo avatar Nov 22 '22 01:11 kevmoo