我有一个我序列化的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)
Pav*_*ets 141
如果您System.Web.Script.Serialization在.NET框架中使用,则可以将ScriptIgnore属性放在不应序列化的成员上.请参阅此处的示例:
考虑以下(简化)案例:
Run Code Online (Sandbox Code Playgroud)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和Name属性,因此生成的JSON对象将如下所示:
Run Code Online (Sandbox Code Playgroud){ Id: 3, Name: 'Test User' }
PS.不要忘记为此添加" System.Web.Extensions" 的引用
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
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将仅被序列化
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)
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
| 归档时间: |
|
| 查看次数: |
232433 次 |
| 最近记录: |