Since your goal is to ignore the property when serializing, but not deserializing, you can use ContractResolver .
Note that the following class does just that and is based on CamelCasePropertyNamesContractResolver to make sure it is serialized in Json fields on a camel basis. If you do not want this, you can inherit it from DefaultContractResolver .
Also, the example I had is based on a string name, but you can easily check if a property is decorated with your custom attribute instead of comparing the property name.
public class CamelCaseIgnoringPropertyJsonResolver<T> : CamelCasePropertyNamesContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) {
Then you can use it as follows:
static private string SerializeMyObject(object myObject) { var settings = new JsonSerializerSettings { ContractResolver = new CamelCaseIgnoringPropertyJsonResolver<JsonIgnoreSerializeAttribute>() }; var json = JsonConvert.SerializeObject(myObject, settings); return json; }
Finally, the user attribute can be of any type, but as per the example:
internal class JsonIgnoreSerializeAttribute : Attribute { }
The approach is tested, and also works with nested objects.
source share