简体   繁体   English

使用Json.NET序列化时忽略特定的数据类型?

[英]Ignoring specific data type when serializing with Json.NET?

I'm saving JSON objects into the database, sometimes it grows very large (I have an object of length 205,797 characters) I want to eliminate the size as possible as I can. 我将JSON对象保存到数据库中,有时它会变得非常大(我有一个长度为205,797个字符的对象)我想尽可能地消除大小。 these objects have a lot of GUID fields, all I don't need, It may help eliminating the size if there is a way to ignore any GUID type from serializing. 这些对象有很多GUID字段,我不需要它,如果有一种方法可以忽略序列化中的任何GUID类型,它可能有助于消除大小。

This is my code, I pass an object of any model type in my application: 这是我的代码,我在我的应用程序中传递任何模型类型的对象:

 public static string GetEntityAsJson(object entity)
 {
     var json = JsonConvert.SerializeObject(entity, Formatting.None, new JsonSerializerSettings
     {
         ReferenceLoopHandling = ReferenceLoopHandling.Ignore
     });
     return json;
}

EDIT 编辑

I don't want to use JsonIgnore attribute, as I will have to add it to so many classes each has a lot of GUID properties, I'm looking for something straight forward like: IgnoreDataType = DataTypes.GUID 我不想使用JsonIgnore属性,因为我必须将它添加到许多类中,每个类都有很多GUID属性,我正在寻找类似的东西: IgnoreDataType = DataTypes.GUID

You can use a custom ContractResolver to ignore all properties of a specific data type in all classes. 您可以使用自定义ContractResolver忽略所有类中特定数据类型的所有属性。 For example, here is one that ignores all Guids : 例如,这里忽略所有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;
    }
}

To use the resolver, just add it to your JsonSerializerSettings : 要使用解析器,只需将其添加到JsonSerializerSettings

var json = JsonConvert.SerializeObject(entity, Formatting.None, new JsonSerializerSettings
{
    ContractResolver = new IgnoreGuidsResolver(),
    ...
});

Demo fiddle: https://dotnetfiddle.net/lOOUfq 演示小提琴: https//dotnetfiddle.net/lOOUfq

Using [JsonIgnore] in your entity class should solve your problem. 在实体类中使用[JsonIgnore]可以解决您的问题。

public class Plane
{
  // included in JSON
  public string Model { get; set; }
  public DateTime Year { get; set; }

  // ignored
  [JsonIgnore]
  public DateTime LastModified { get; set; }
}

You can create your own Converter 您可以创建自己的转换器

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);
    }
}

And use it as 并用它作为

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);
    }

Classes

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; }

}

I used this reference to Create the converter Json.NET, how to customize serialization to insert a JSON property 我使用此引用创建转换器Json.NET,如何自定义序列化以插入JSON属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM