I'm trying to just serialize settable properties using Json.NET. I have a custom ContractResolver
and am trying to ignore readonly properties using the Writable property of a JsonProperty
class.
The test below fails. I would expect that the property is 'Writable = true' because there is only a 'get' definition on the property Bar.
Is there another way of doing this?
As a side note, the reason for serializing this way is that it will save a lot of unnecessary properties serializations. The source and destination object will be the same, so there's not much point in loading up the json with unnecessary properties.
[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"));
}
}