Serialization Json.NET-有条件序列化

Serialization Json.NET-有条件序列化,serialization,json.net,conditional-statements,Serialization,Json.net,Conditional Statements,Json.NET是否可以有条件地序列化对象: class Test { public string Id {get;set;} public string Value {get;set;} public List<Extension> Extensions {get;set;} } 如果设置了Id或扩展名: "Test": { "Id": "1", "Value": "fromvalue", "Extensions": [

Json.NET是否可以有条件地序列化对象:

class Test
{
     public string Id {get;set;}
     public string Value {get;set;}
     public List<Extension> Extensions {get;set;}
}
如果设置了Id或扩展名:

"Test": {
     "Id": "1",
     "Value": "fromvalue",
     "Extensions": [ {...}, {...}]
}
甚至:

"Test": "fromvalue",
"_Test": {
     "Id": "1",
     "Extensions": [ {...}, {...}]
}

实现这一点的一种方法是使用一个带有条件的方法。比如说,

将测试类重写为

class Test
{

     public string Id {get;set;}
     public string Value {get;set;}
     public List<int> Extensions {get;set;}

     public bool ShouldSerializeId()=> !(string.IsNullOrEmpty(Id) && Extensions == null);
     public bool ShouldSerializeExtensions()=>  !(string.IsNullOrEmpty(Id) && Extensions == null);
}
现在可以将json反序列化为

var serializerSettings = new JsonSerializerSettings()
                            {
                                ContractResolver = new CustomContractResolver((!testObject.ShouldSerializeId() && !testObject.ShouldSerializeExtensions()))
                            };
var json = JsonConvert.SerializeObject(testObject,serializerSettings);

您看过了吗?是的,我看过了,但没有提供问题中描述的功能。
public class CustomContractResolver : DefaultContractResolver
{
    public bool UseTypeName { get; }

    public CustomContractResolver(bool useTypeName)
    {
        UseTypeName  = useTypeName;
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (UseTypeName && property.PropertyName.Equals(nameof(Test.Value)))
            property.PropertyName = property.DeclaringType.Name;

        return property;
    }
}
var serializerSettings = new JsonSerializerSettings()
                            {
                                ContractResolver = new CustomContractResolver((!testObject.ShouldSerializeId() && !testObject.ShouldSerializeExtensions()))
                            };
var json = JsonConvert.SerializeObject(testObject,serializerSettings);