如何从Json序列化中排除属性

Ela*_*nda 216 c# json

我有一个我序列化的DTO类

Json.Serialize(MyClass)
Run Code Online (Sandbox Code Playgroud)

我怎样才能排除它的公共财产?

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

JC *_*aja 330

如果您使用的是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; }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用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; }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size

  • 如果我是OP,我宁愿选择[ScriptIgnore]解决方案.主要是由于Json解决方案的一致性所以Json问题.当您使用的库提供解决方案时,为什么要涉及System.Web.Extensions?绝对最好的IMHO是[IgnoreDataMember]属性,因为System.Runtime.Serialization应该与每个序列化程序兼容,如果你想换掉Json. (36认同)
  • 注意你的命名空间。[JsonIgnore] 属性存在于 Newtonsoft.Json 和 System.Text.Json.Serialization 命名空间中。在模型上使用 Newtonsoft.Json.JsonIgnore 很容易,然后使用 System.Text.Json.Serialization.JsonSerializer.Serialize 来序列化模型(反之亦然)。然后 JsonIgnore 属性将被忽略。:) (3认同)
  • @user123456 如果 value 为 null,为什么在反序列化时要忽略?为什么不只为一个属性设置一个空值,或者创建一个优雅地处理空值的属性? (2认同)

Pav*_*ets 141

如果您System.Web.Script.Serialization在.NET框架中使用,则可以将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); }
    } 
} 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,只会序列化Id和Name属性,因此生成的JSON对象将如下所示:

{ Id: 3, Name: 'Test User' }
Run Code Online (Sandbox Code Playgroud)

PS.不要忘记为此添加" System.Web.Extensions" 的引用

  • 我在`System.Web.Script.Serialization`命名空间中找到了`ScriptIgnore`. (10认同)

Ale*_*lex 68

对不起,我决定写另一个答案,因为其他答案都不够复制粘贴。

如果您不想使用某些属性装饰属性,或者您无法访问该类,或者您想决定在运行时序列化什么等等,那么您可以在 Newtonsoft.Json 中执行此操作

//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
    private readonly HashSet<string> ignoreProps;
    public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
    {
        this.ignoreProps = new HashSet<string>(propNamesToIgnore);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        if (this.ignoreProps.Contains(property.PropertyName))
        {
            property.ShouldSerialize = _ => false;
        }
        return property;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
        { ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) });
Run Code Online (Sandbox Code Playgroud)

注意:ContractResolver如果您决定使用此答案,请确保缓存对象,否则性能可能会受到影响。

我已经在这里发布了代码以防有人想添加任何东西

https://github.com/jitbit/JsonIgnoreProps

  • 精彩的答案!您还可以使用 public IgnorePropertiesResolver(params string[] propNamesToIgnore) 作为构造函数,以便实现者可以说 new IgnorePropertiesResolver("Prop1", "Prop2")` (3认同)
  • 奇迹般有效。请注意,如果您需要与另一个解析器(例如“CamelCasePropertyNamesContractResolver”)组合,只需使用“IgnorePropertiesResolver”(考虑到组合,可能会重命名为更准确的名称)并从“CamelCasePropertyNamesContractResolver”继承,而不是直接从“DefaultContractResolver”继承。 (2认同)
  • 我为自己做了一个小更改...而不是构造函数采用 IEnumerable&lt;string&gt;,我的构造函数采用 IEnumerable&lt;PropertyInfo&gt;...这样您就不能传递拼写错误的属性名称。调用者需要使用 Type.GetProperty 从字符串中获取 PropertyInfo (2认同)
  • 感谢很好的答案,我想补充一点,它也可以用于忽略反序列化,这是建议确保属性也被反序列化忽略的所有属性。property.ShouldSerialize = _ =&gt; false; 属性.忽略= true; 属性.Readable = false; property.ShouldDeserialize = _ =&gt; false; 属性.Writable = false; (2认同)

Ari*_*ion 30

你可以使用[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); }
    }
}
Run Code Online (Sandbox Code Playgroud)

参考这里

在这种情况下,Id和then name将仅被序列化

  • 我知道这是一个旧评论,但是是的,在 MVC 控制器中使用 `[ScriptIgnore]`。但是请注意,如果您使用 *SignalR*,那么您也应该使用 `[JsonIgnore]`。 (2认同)

tym*_*tam 19

对于 C# 9 的记录是[property: JsonIgnore]

using System.Text.Json.Serialization;

public record R(
   string Text2
   [property: JsonIgnore] string Text2)
Run Code Online (Sandbox Code Playgroud)

对于经典风格来说,它仍然只是[JsonIgnore]

using System.Text.Json.Serialization;

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

   [JsonIgnore] 
   public string Text2 { get; init; }
}
Run Code Online (Sandbox Code Playgroud)


Thu*_*kwa 13

如果你不是那么热衷于像我一样用属性来装饰代码,尤其是当你在编译时无法告诉我这里会发生什么是我的解决方案.

使用Javascript Serializer

    public static class JsonSerializerExtensions
    {
        public static string ToJsonString(this object target,bool ignoreNulls = true)
        {
            var javaScriptSerializer = new JavaScriptSerializer();
            if(ignoreNulls)
            {
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
            }
            return javaScriptSerializer.Serialize(target);
        }

        public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
        {
            var javaScriptSerializer = new JavaScriptSerializer();
            foreach (var key in ignore.Keys)
            {
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
            }
            return javaScriptSerializer.Serialize(target);
        }
    }


public class PropertyExclusionConverter : JavaScriptConverter
    {
        private readonly List<string> propertiesToIgnore;
        private readonly Type type;
        private readonly bool ignoreNulls;

        public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
        {
            this.ignoreNulls = ignoreNulls;
            this.type = type;
            this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();
        }

        public PropertyExclusionConverter(Type type, bool ignoreNulls)
            : this(type, null, ignoreNulls){}

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            var result = new Dictionary<string, object>();
            if (obj == null)
            {
                return result;
            }
            var properties = obj.GetType().GetProperties();
            foreach (var propertyInfo in properties)
            {
                if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
                {
                    if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
                    {
                         continue;
                    }
                    result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
                }
            }
            return result;
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 逻辑上的微小变化和 `PropertyExclusionConverter` 可以变成一个 `PropertyInclusionConverter`。 (2认同)
  • 这样做的一个潜在问题是,每次序列化对象时,它都必须一遍又一遍地执行名称匹配和排除工作。但是,一旦编译,类型的属性就不会改变——您应该预先计算每个类型应包含的名称,然后重用每行上的列表。对于非常庞大的 JSON 序列化作业,缓存可能会显着提高性能。 (2认同)

Tra*_*vis 11

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

官方 Microsoft Docs:JsonIgnoreAttribute

如前所述这里

该库作为 .NET Core 3.0 共享框架的一部分内置。
对于其他目标框架,请安装 System.Text.Json NuGet 包。该软件包支持:

  • .NET Standard 2.0 及更高版本
  • .NET Framework 4.6.1 及更高版本
  • .NET 核心 2.0、2.1 和 2.2