【问题标题】:Ignore property if exists in System.Text.json. Parameter type is object如果 System.Text.json 中存在,则忽略属性。参数类型为对象
【发布时间】:2020-10-08 12:40:00
【问题描述】:

我在某些应用程序响应期间使用 .NET Core 3.1 我正在对日志进行对象序列化。

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

一个对象就像

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

只有在序列化过程中存在的情况下,我才可以忽略某个特定属性(比如id_token)的任何可能性

object result = FromSomeCall();

可以产生多种类型的对象。

【问题讨论】:

标签: c# serialization .net-core-3.1 system.text.json


【解决方案1】:

已使用变通方法首先将我的对象转换为动态,然后更改值(我也可以在此处删除)

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));
        }

使用以下扩展方法

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;
        }

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多