Json シリアル化からプロパティを除外する方法 質問する

Json シリアル化からプロパティを除外する方法 質問する

私はシリアル化するDTOクラスを持っています

Json.Serialize(MyClass)

パブリックプロパティを除外するにはどうすればよいでしょうか?

(他の場所のコードで使用するため、公開する必要があります)

ベストアンサー1

Json.Net属性を使用している場合[JsonIgnore]、シリアル化または逆シリアル化中にフィールド/プロパティは単に無視されます。

public class Car
{
  // included in JSON
  public string Model { get; set; }
  public DateTime Year { get; set; }
  public List<string> Features { get; set; }

  // ignored
  [JsonIgnore]
  public DateTime LastModified { get; set; }
}

または、DataContract と DataMember 属性を使用して、プロパティ/フィールドを選択的にシリアル化/逆シリアル化することもできます。

[DataContract]
public class Computer
{
  // included in JSON
  [DataMember]
  public string Name { get; set; }
  [DataMember]
  public decimal SalePrice { get; set; }

  // ignored
  public string Manufacture { get; set; }
  public int StockCount { get; set; }
  public decimal WholeSalePrice { get; set; }
  public DateTime NextShipmentDate { get; set; }
}

参照するhttp://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size詳細については

おすすめ記事