私の解決策:
class MyContractResolver : DefaultContractResolver
{
private JsonObjectContract objectContract = null;
public override JsonContract ResolveContract(Type type)
{
JsonContract contract = base.ResolveContract(type);
objectContract = contract as JsonObjectContract;
return contract;
}
public void RemoveProperty(string name)
{
if (objectContract != null)
{
objectContract.Properties.Remove(objectContract.Properties.First(
p => p.PropertyName == name));
}
}
public void AtomarOptinalType(string name, bool specified)
{
if (objectContract != null)
{
if (!specified)
{
JsonProperty prop = objectContract.Properties.First(
p => p.PropertyName == name);
objectContract.Properties.Remove(prop);
}
RemoveProperty(name + "Specified");
}
}
}
次に、生成されたクラスの拡張で:
public partial class MyGeneratedClass
{
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
this.PropertyChanged +=
new System.ComponentModel.PropertyChangedEventHandler(
MyGeneratedClass_PropertyChanged);
}
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
MyContractResolver cr = context.Context as MyContractResolver;
if (cr != null)
{
cr.AtomarOptinalType("MyAtomarOptionalProperty",
this.MyAtomarOptionalPropertySpecified);
}
}
void MyGeneratedClass_PropertyChanged(object sender,
System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "MyAtomarOptionalProperty")
{
this.MyAtomarOptionalPropertySpecified = true;
}
}
}