我有一个DTO类,我序列化

Json.Serialize(MyClass)

我如何排除该物业的公共财产?

(它必须是公共的,因为我在其他地方的代码中使用它)


当前回答

对于c# 9的记录,它是[property: JsonIgnore]

using System.Text.Json.Serialization;

public record R(
   string Text2
   [property: JsonIgnore] string Text2)

对于经典样式,它仍然只是[JsonIgnore]。

using System.Text.Json.Serialization;

public record R
{
   public string Text {get; init; }

   [JsonIgnore] 
   public string Text2 { get; init; }
}

其他回答

如果你使用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

如果你正在使用System.Text.Json,那么你可以使用[JsonIgnore]。 FQ: System.Text.Json.Serialization.JsonIgnoreAttribute

官方微软文档:JsonIgnoreAttribute

如下所述:

该库是作为. net Core 3.0共享框架的一部分内置的。 对于其他目标框架,安装System.Text.Json NuGet 包中。该软件包支持: .NET标准2.0及更高版本 .NET Framework 4.6.1及以上版本 .NET Core 2.0, 2.1和2.2

如果你在。net框架中使用System.Web.Script.Serialization,你可以把ScriptIgnore属性放在不应该被序列化的成员上。请看下面的例子:

考虑以下(简化)情况: 公共类用户{ 公共int Id{获取;设置;} 公共字符串名称{获取;设置;} (ScriptIgnore) public bool IsComplete { string.IsNullOrEmpty(Name);} } } 在这种情况下,只有Id和Name属性会被序列化,因此生成的JSON对象看起来像这样: {Id: 3,名称:'测试用户'}

另外,不要忘记添加对“System.Web”的引用。扩展”

你可以使用[ScriptIgnore]:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ScriptIgnore]
    public bool IsComplete
    {
        get { return Id > 0 && !string.IsNullOrEmpty(Name); }
    }
}

在这种情况下,Id和名称只会被序列化

您也可以使用[NonSerialized]属性

[Serializable]
public struct MySerializableStruct
{
    [NonSerialized]
    public string hiddenField;
    public string normalField;
}

来自微软文档:

指示可序列化类的字段不应被序列化。这个类不能被继承。


例如,如果你使用Unity(这不仅仅适用于Unity),那么这适用于UnityEngine。JsonUtility

using UnityEngine;

MySerializableStruct mss = new MySerializableStruct 
{ 
    hiddenField = "foo", 
    normalField = "bar" 
};
Debug.Log(JsonUtility.ToJson(mss)); // result: {"normalField":"bar"}