繁体   English   中英

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

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

我将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(),
    ...
});

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

在实体类中使用[JsonIgnore]可以解决您的问题。

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,如何自定义序列化以插入JSON属性

暂无
暂无

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

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