簡體   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