c# - Json.Net 中的自定义属性处理

标签 c# json json.net

我的目标是序列化没有任何属性的属性和具有特定自定义属性的属性。

对于以下类(class):

public class Msg
{
    public long Id { get; set; }

    [CustomAttributeA]
    public string Text { get; set; }

    [CustomAttributeB]
    public string Status { get; set; }
}

当我调用方法Serialize(object, CustomAttributeA)时,我希望得到以下输出:

{
    "Id" : someId,
    "Text" : "some text"
}

当我调用 Serialize(object, CustomAttributeB) 时,我想要以下内容:

{
    "Id" : someId,
    "Status" : "some status"
}

我读到可以通过创建自定义 ContractResolver 来实现此目的,但在这种情况下我必须创建两个单独的合约解析器吗?

最佳答案

您不需要两个单独的解析器来实现您的目标。只需将自定义 ContractResolver 设为通用,其中类型参数表示您在序列化时要查找的属性。

例如:

public class CustomResolver<T> : DefaultContractResolver where T : Attribute
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);

        foreach (JsonProperty prop in list)
        {
            PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
            if (pi != null)
            {
                // if the property has any attribute other than 
                // the specific one we are seeking, don't serialize it
                if (pi.GetCustomAttributes().Any() &&
                    pi.GetCustomAttribute<T>() == null)
                {
                    prop.ShouldSerialize = obj => false;
                }
            }
        }

        return list;
    }
}

然后,您可以创建一个辅助方法来创建解析器并序列化您的对象:

public static string Serialize<T>(object obj) where T : Attribute
{
    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        ContractResolver = new CustomResolver<T>(),
        Formatting = Formatting.Indented
    };
    return JsonConvert.SerializeObject(obj, settings);
}

当你想要序列化时,请像这样调用助手:

string json = Serialize<CustomAttributeA>(msg);

演示 fiddle :https://dotnetfiddle.net/bRHbLy

关于c# - Json.Net 中的自定义属性处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43494923/

相关文章:

java - 无法从另一个类获取 ArrayList。它总是空的

c# - 对 JTokenTypes 的双重/长期支持?

c# - C# 中的链式构造函数 - 使用中间逻辑

json - 如何在 Go 中从 interface{} 解码到 interface{}

c# - Xamarin.iOS Objective-C 绑定(bind)错误

java - 使用通用 'header' 增强 Spring Rest API

c# - 将平面字典序列化为多子对象 JSON

C# 从序列化的 json 数组访问值

c# - 从 amazon s3 流式传输文件

c# - 在 c# 中将字符串转换为 xml 会出现空白错误