继承DefaultContractResolver并以不同的方式处理引用的实体



我只想序列化更改的属性。我设法为根类型做了这件事,但它包含对其他要序列化的对象的引用(甚至可能是相同类型的对象)。

这是我的接口和合同解析器:

public interface ISelectiveJsonSerialize
{
    IList<string> PropertiesToSerialize { get; }
}
public class JsonSelectiveSerializeContractResolver : DefaultContractResolver
{
    private readonly IList<string> _propertiesToSerialize;
    public JsonSelectiveSerializeContractResolver(IList<string> propertiesToSerialize)
    {
        _propertiesToSerialize = propertiesToSerialize;
    }
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return base.CreateProperties(type, memberSerialization).Where(p => _propertiesToSerialize.Contains(p.PropertyName)).ToList();
    }
}

属性PropertiesToSerialize将有一个接收值的属性名列表。

我是这样序列化的:

        string result = "";
        if (val is ISelectiveJsonSerialize)
        {
            // Don't serialize all properties
            var resolver = new JsonSelectiveSerializeContractResolver(((ISelectiveJsonSerialize)val).PropertiesToSerialize);
            var settings = new JsonSerializerSettings { ContractResolver = resolver };
            result = JsonConvert.SerializeObject(val, Formatting.None, settings);
        }
        else
        {
            // Default serialization
            result = JsonConvert.SerializeObject(val);
        }
        return result;

这是一个我可以序列化的类型的例子:

public class Category : BaseType
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            PropertiesToSerialize.Add("Name");
        }
    }
    private Category _category;
    public Category Category
    {
        get { return _category; }
        set
        {
            _category = value;
            PropertiesToSerialize.Add("Category");
        }
    }
}

你可以理解,如果我只为我的根类型设置一个类别,它不会序列化这个名称,因为根PropertiesToSerialize不包含"name",如果它会序列化它会序列化根实体的空名称。

帮助吗?

可以钩入Json的条件属性序列化功能。. NET添加测试以确定给定属性在序列化之前是否已被修改:

public class JsonSelectiveSerializeContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        var shouldSerialize = property.ShouldSerialize;
        var name = property.PropertyName;
        property.ShouldSerialize = (o) =>
        {
            var selectiveSerialize = o as ISelectiveJsonSerialize;
            if (selectiveSerialize != null)
            {
                if (!selectiveSerialize.PropertiesToSerialize.Contains(name))
                    return false;
            }
            return shouldSerialize == null || shouldSerialize(o);
        };
        return property;
    }
}

样本小提琴。

相关内容

  • 没有找到相关文章

最新更新