代码之家  ›  专栏  ›  技术社区  ›  mshwf

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

  •  6
  • mshwf  · 技术社区  · 9 年前

    我正在将JSON对象保存到数据库中,有时它会变得非常大(我有一个长度为205797个字符的对象),我希望尽可能消除大小。这些对象有很多GUID字段,我不需要这些字段,如果有办法忽略序列化中的任何GUID类型,这可能有助于消除大小。

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

    编辑

    我不想使用 JsonIgnore 我正在寻找一些直接的东西,比如: IgnoreDataType = DataTypes.GUID

    3 回复  |  直到 9 年前
        1
  •  6
  •   Brian Rogers    9 年前

    您可以使用自定义 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

        2
  •  0
  •   André    9 年前

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

    public class Plane
    {
      // included in JSON
      public string Model { get; set; }
      public DateTime Year { get; set; }
    
      // ignored
      [JsonIgnore]
      public DateTime LastModified { get; set; }
    }
    
        3
  •  0
  •   M.Almokadem    9 年前

    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