我正在将 JSON 对象保存到数据库中,有时它会变得非常大(我有一个长度为 205,797 个字符的对象)我想尽可能地减少大小。这些对象有很多我不需要的 GUID 字段,如果有一种方法可以忽略序列化中的任何 GUID 类型,它可能有助于消除大小。
这是我的代码,我在我的应用程序中传递了一个任何模型类型的对象:
public static string GetEntityAsJson(object entity)
{
var json = JsonConvert.SerializeObject(entity, Formatting.None, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return json;
}
编辑
我不想使用 JsonIgnore
属性,因为我必须将它添加到这么多类中,每个类都有很多 GUID 属性,
我正在寻找直截了当的东西,例如:
IgnoreDataType = DataTypes.GUID
最佳答案
您可以使用自定义 ContractResolver
来忽略所有类中特定数据类型的所有属性。例如,这是一个忽略所有 Guids
的例子:
class IgnoreGuidsResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (prop.PropertyType == typeof(Guid))
{
prop.Ignored = true;
}
return prop;
}
}
要使用解析器,只需将其添加到您的JsonSerializerSettings
:
var json = JsonConvert.SerializeObject(entity, Formatting.None, new JsonSerializerSettings
{
ContractResolver = new IgnoreGuidsResolver(),
...
});
演示 fiddle :https://dotnetfiddle.net/lOOUfq
关于c# - 使用 Json.NET 序列化时忽略特定数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569855/