0

I am using .NET Core 3.1 during some application response I am doing object serialization for logging.

object result = FromSomeCall();
Logger.DebugFormat("Final Response against {0}", JsonSerializer.Serialize(result.Value));

One object is like

{
    "auth_req_id": ".....",
    "expires_in": 1800,
    "correlation_id": null,
    "access_token": "..==",
    "token_type": "Bearer",
    "id_token": "....."
}

Any possibility that I can ignore one particular property (let's say here id_token) only if it exists during serialization

object result = FromSomeCall();

Can result in multiple type of objects.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93
  • If you have control over class your json is deserialized you can mark property with [JsoniIgnoreAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonignoreattribute?view=netcore-3.1) – Guru Stron Jun 18 '20 at 12:51
  • `JsonIgnoreAttribute`? – bolkay Jun 18 '20 at 12:52
  • [Exclude properties from serialization](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#exclude-properties-from-serialization) will provide you some ideas – Pavel Anikhouski Jun 18 '20 at 12:56
  • Do you mean you want to include the property during **deserialization** but exclude it during **serialization**? – dbc Jun 18 '20 at 15:20
  • exclude it during serialization. Basically FromSomeCall return different anonymous class object as per condition which i am generating like new {test="1",id_token="2"} or like new {errorcode="1",error_description="asdasd"} e.t.c. – Kamran Shahid Jun 18 '20 at 17:10
  • I myself have done something which i am not remembering where i have ignored the properties during serialization. May be i have did it in newtonsoft or system.text.json – Kamran Shahid Jun 18 '20 at 17:13
  • With newtonsoft you can do it using a custom contract resolver, see e.g. [Exclude property from serialization via custom attribute (json.net)](https://stackoverflow.com/q/13588022/3744182). You could also use conditional serialization, see e.g. [NewtonSoft add JSONIGNORE at runTime](https://stackoverflow.com/q/25157511/3744182). And to literally deserialize but not serialize see [Making a property deserialize but not serialize with json.net](https://stackoverflow.com/q/11564091/3744182). – dbc Jun 18 '20 at 17:50
  • 1
    But [tag:system.text.json] doesn't have most of that functionality. No access to its contract resolver, no conditional serialization. You could write a custom `JsonConverter` like the one here: [How to exclude a property from being serialized in System.Text.Json.JsonSerializer.Serialize() using a JsonConverter](https://stackoverflow.com/q/58566735/3744182). Or you could serialize to `JsonDocument` and filter later, see [Modifying a JSON file using System.Text.Json](https://stackoverflow.com/a/59001666/3744182). – dbc Jun 18 '20 at 17:53

1 Answers1

0

Have used a work around to first convert my object to dynamic and then change the value (i can also remove here)

private void LogWithExludedProperty(object value, string key)
        {
            dynamic copiedValue = value.ToDynamic();
            if (copiedValue is ExpandoObject)
            {
                if (((IDictionary<string, dynamic>)copiedValue).ContainsKey(key))
                {
                    ((IDictionary<string, dynamic>)copiedValue)[key] = ".....";
                }
            }

            Logger.DebugFormat("Final Response Token:{0}", JsonSerializer.Serialize(copiedValue));
        }

use following extension method

public static dynamic ToDynamic(this object value)
        {
            IDictionary<string, object> expando = new ExpandoObject();

            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
                expando.Add(property.Name, property.GetValue(value));

            return expando as ExpandoObject;
        }
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93