json.net を使用して、クラスのプロパティが null の場合に無視する方法 質問する

json.net を使用して、クラスのプロパティが null の場合に無視する方法 質問する

使っていますJson.NETクラスを JSON にシリアル化します。

次のようなクラスがあります:

class Test1
{
    [JsonProperty("id")]
    public string ID { get; set; }
    [JsonProperty("label")]
    public string Label { get; set; }
    [JsonProperty("url")]
    public string URL { get; set; }
    [JsonProperty("item")]
    public List<Test2> Test2List { get; set; }
}

の場合にのみ、プロパティJsonIgnore()に属性を追加したいと思います。 null でない場合は、それを json に含めたいと思います。Test2ListTest2Listnull

ベストアンサー1

属性を使用した代替ソリューションJsonProperty:

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
// or
[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]

// or for all properties in a class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]

ご覧の通りこのオンラインドキュメント

おすすめ記事