2

How to find out if called from Serializiaton or deserialization ?

I need something like this:

protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
{
    IValueProvider valueProvider = base.CreateMemberValueProvider(member);

    if (member.CustomAttributes.First().AttributeType == typeof(EncryptedAttribute))
    {
        object value = valueProvider.GetValue(_object);
        if(IsInSerialization())
        {
            valueProvider.SetValue(_object, Encrypt(value));
        }
        else
        {
            valueProvider.SetValue(_object, Decrypt(value));
        }
    }
    return valueProvider;
}
Felix D.
  • 4,811
  • 8
  • 38
  • 72
  • 1
    You have no way to know this from within the contract resolver itself, especially since the contracts are shared between serialization and deserialization. You could 1) Use a different resolver for serialization and deserialization, or 2) [`IValueProvider`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_IValueProvider.htm) anyway has both `SetValue` and `GetValue`, you could do the correct thing in each. Related: [How can I encrypt selected properties when serializing my objects?](https://stackoverflow.com/q/29196809/3744182). – dbc Sep 04 '18 at 15:01
  • @dbc i guess 2) is the most handy. how would I change the IValueProvider for the selected property ? – Felix D. Sep 04 '18 at 15:03
  • Well the linked question [How can I encrypt selected properties when serializing my objects?](https://stackoverflow.com/q/29196809/3744182) shows exactly how. Another example of a custom value provider can be see in [NewtonSoft JsonConverter - Access other properties](https://stackoverflow.com/a/47872645) – dbc Sep 04 '18 at 15:07
  • @dbc yeah true.. i seem to be blind. Thanks for your help - it's working perfectly. if u feel like posting that as an answer or closing as a dupe im down ! – Felix D. Sep 04 '18 at 15:18
  • And also: [*Overriding a property value in custom JSON.net contract resolver*](https://stackoverflow.com/q/46977905) and [this answer to *Json Convert empty string instead of null*](https://stackoverflow.com/a/35620248). Can this be closed off as a dup, or do you need more specific help? – dbc Sep 04 '18 at 15:18
  • OK, done. Glad to help. – dbc Sep 04 '18 at 15:19

0 Answers0