0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ForeignKeyAttributeが付いていたらJsonIgnoreする

Posted at

Navigationプロパティを使っている場合、JsonとしてSerializeするときに循環参照する事があります
少々、強引ですがForeignKeyAttributeが付いているプロパティをJsonIgnoreするContractResolverです
JsonIgnoreAttibuteを使うという方法もありますが設定数が多くなるため書きました

public class ForeignKeyIgnoreContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        var foreignKeyAttribute = member.GetCustomAttribute<ForeignKeyAttribute>();
        if (foreignKeyAttribute != null)
        {
            property.Ignored = true;
        }
        return property;
    }
}

デフォルト設定として使う場合

var settings = new JsonSerializerSettings
{
    ContractResolver = new ForeignKeyIgnoreContractResolver()
};
JsonConvert.DefaultSettings = () => settings;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?