Q:

Force serialization of property that has [JsonIgnore] attribute

Is it possible to somehow force serialization of x property?
public class Cake
{
    [JsonIgnore]
    // possibly some attribute like [ReadOnlyJsonIgnore] or [JsonIgnoreReadOnly] would be nice
    public int x { get; set; }
}

But keep [JsonIgnore] for deserialization only? What I want to achieve is some form of read only properties. So they can be serialized but can't be deserialized, are simply ignored like they aren't there.

A:

Okay, what I did to make this "force" work(a bit hackish):
I created custom JsonConverter that use custom IContractResolver that ignores [JsonIgnore] only for writing in WriteJson.
public class CustomJsonConverter : JsonConverter
{
    ...

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // somehow using serializer passed to this method doesn't seem to work
        var token = JToken.FromObject(value, new JsonSerializer()
        {
            ContractResolver = new DontIgnoreContractResolver()
        });
        token.WriteTo(writer);
    }
}

public class DontIgnoreContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var jsonProperty = base.CreateProperty(member, memberSerialization);
        if (jsonProperty.Ignored)
        {
            jsonProperty.Ignored = false;
        }
        return jsonProperty;
    }
}

but for ReadJson it uses default contract resolver and ignores the property. But yeah, that's possible.

