YAML/JSON::Serializable tweak

I’m migrating an ORM away from using JSON.mapping and have a situation where I want to ignore fields when serializing or de-serializing selectively.

Currently there is the @[JSON::Field(ignore: true)] but would be nice to be able to configure this for either direction.

something like deserialize: false / serialize: false where they both default to true.
Happy to make a pull request if there is interest

1 Like

I brought this up before: https://github.com/crystal-lang/crystal/issues/6406

It didn’t seem to get that much support, so I made a shard for it: https://github.com/athena-framework/serializer

1 Like

That would be a breaking change so I don’t think we can do it.

Why do you need it just in one way?

A common scenario that comes to mind is user registration. I.e. you would want to be able to POST:

{
  "first_name": "foo",
  "last_name": "bar",
  "email": "fakeemail@domain.com",
  "password": "monkey123"
}

And the response should be:

{
  "id": 1,
  "first_name": "foo",
  "last_name": "bar",
  "email": "fakeemail@domain.com",
  "created_at": "2020-06-10T04:09:16Z",
  "updated_at": "2020-06-10T04:09:16Z"
}

I.e. allows an application to deserialize the password, but then doesn’t expose it again.

EDIT: https://athena-framework.github.io/serializer/Athena/Serializer/Annotations/IgnoreOnSerialize.html

1 Like

In that case you can have two objects, one with the password property, one without it.

But yeah, if we want to add it maybe we can have:

  • ignore: if true, both serialize and deserialize are ignored, and it has precedence over the other two
  • ignore_serialize: if true, only ignores on serialization
  • ignore_deserialize: if true, only ignores on deserialization

What do you think?

3 Likes

@Blacksmoke16 that is the exact situation where this came up.
@asterite I don’t think it would be a breaking change, totally in support of ignore_serialize and ignore_deserialize I think it would be super useful.

@stakach Great! Feel free to send a PR, though there’s no guarantee it will go in (as usual).

1 Like