我正在尝试使用Json.NET序列化可设置的属性。我有一个自定义ContractResolver
,并尝试使用JsonProperty
类的Writable属性忽略readonly属性。
以下测试失败。我希望该属性是'Writable = true',因为属性栏上只有一个'get'定义。
还有另一种方法吗?
作为旁注,这种序列化的原因是它将节省许多不必要的属性序列化。源和目标对象将是相同的,因此用不必要的属性加载json没有多大意义。
[TestClass]
public class JsonDotNet_WriteOnlyTests
{
private class FooContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, MemberSerialization.Fields);
//ignore all readonly properties
var readOnlyProps = properties.Where(w => !w.Writable);
foreach (var readonlyProp in readOnlyProps)
{
readonlyProp.Ignored = true;
}
return properties;
}
}
private class Foo
{
public string Name { get; set; }
//I would expect this property to be 'Writable=false'...
public string Bar { get { return "Hey there"; } }
}
[TestMethod]
public void TestWriteOnly()
{
var settings = new JsonSerializerSettings
{
ContractResolver = new FooContractResolver()
};
var foos = new []{new Foo{}, new Foo{}};
var json = JsonConvert.SerializeObject(foos, settings);
Assert.IsFalse(json.Contains("Bar"));
}
}