使用Json.NET序列化时忽略特定的数据类型?
问题描述:
我正在将JSON对象保存到数据库中,有时它会变得非常大(我有一个长度为205,797个字符的对象)我想尽可能消除大小。这些对象有很多GUID字段,我不需要它们,如果有一种方法可以忽略任何序列化的GUID类型,它可能有助于消除大小。使用Json.NET序列化时忽略特定的数据类型?
这是我的代码,我传递任何模型类型的对象,在我的应用程序:
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(),
...
});
答
使用0123实体类中的应该可以解决您的问题。
public class Plane
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
答
您可以创建自己的转换器
public class MyJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JObject jo = new JObject();
foreach (PropertyInfo prop in value.GetType().GetProperties())
{
if (prop.CanRead)
{
if (prop.PropertyType == typeof(Guid))
continue;
object propValue = prop.GetValue(value);
if (propValue != null)
{
jo.Add(prop.Name, JToken.FromObject(propValue));
}
}
}
jo.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType.IsAssignableFrom(objectType);
}
}
并将其用作
static void Main(string[] args)
{
Person testObj = new Person
{
Id = Guid.NewGuid(),
Name = "M.A",
MyAddress = new Address
{
AddressId = 1,
Country = "Egypt"
}
};
var json = JsonConvert.SerializeObject(testObj, new MyJsonConverter());
Console.WriteLine(json);
}
类
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public Address MyAddress { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string Country { get; set; }
}
我用这个引用创建转换 Json.NET, how to customize serialization to insert a JSON property
我知道,但我将要经过几十个有很多的GUID类的! –
然后,你应该添加这个到你的问题。如果不更改类,您应该可以使用自定义合约解析器执行此操作,如下所述:https://stackoverflow.com/a/25769147/715348 –