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

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

对于以下课程:

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泛型化即可,其中的type参数表示序列化时要查找的属性。

例如:

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

演示小提琴:https://dotnetfiddle.net/bRHbLy

json.dumps弄乱顺序 - python

我正在使用json module创建一个包含类似条目的json文件json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "cou…

JSON PATH字段NULL检查表达式 - java

我有一个像bellow的json数组:{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sa…

JSON.NET如何删除节点 - c#

我有一个像下面这样的json:{ "d": { "results": [ { "__metadata": { }, "prop1": "value1", "prop2": "value2", "__some&#…

json_encode网址失败 - php

有人在this bug附近吗?echo json_encode(array('url'=>'/foo/bar')); {"url":"\/foo\/bar"} 我使用Zend_Json and Zend_Json_Expr以便我甚至可以在js对象中获取回调函数-但我无法获得…

JSON SCHEMA PATTERN逗号分隔列表 - python

我的json模式中具有以下模式,并且我需要根据以下模式包含逗号分隔的值。当前模式只能像DV2一样处理一种模式所以我应该如何修改我的模式以包括多个字符串,如下所示,但它应该与声明的模式匹配。例如:“ DV2”,“ DEV1”,“ DEV3”,“ ST”, "ENVIRONMENT": { "type": "st…