Json_serializable.dart: Implement JsonKey - readonly, writeonly

Created on 28 Nov 2019  路  6Comments  路  Source: google/json_serializable.dart

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.

enhancement

Most helpful comment

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

All 6 comments

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

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

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

Is there any update on this?

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;

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

Was this page helpful?
0 / 5 - 0 ratings