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

时间:2017-08-08 13:35:20

标签: c# json serialization json.net deserialization

我正在将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

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

您可以创建自己的转换器

      @Entity
      @Table(name="clients")
     public class Clients implements Serializable  {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)     
     @OneToMany(mappedBy="clients", cascade=CascadeType.ALL)
      List<SmsNumbers> smsNumbers;

    on the parent side
     and put the following annotation on the child side




 @Entity
  @Table(name="smsnumbers")
 public class SmsNumbers implements Serializable {
   @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
   int id;
   String number;
   String status;
 Date reg_date;
 @ManyToOne
 @JoinColumn(name = "client_id")
 private Clients clients;
  and getter setter.





    public static void main(String arr[])
   {
       Session session = HibernateUtil.openSession();
     //getting transaction object from session object
       session.beginTransaction();

        Clients cl=new Clients("Murali", "1010101010");
          SmsNumbers sms1=new SmsNumbers("99999", "Active", cl);
          SmsNumbers sms2=new SmsNumbers("88888", "InActive", cl);
          SmsNumbers sms3=new SmsNumbers("77777", "Active", cl);
          List<SmsNumbers> lstSmsNumbers=new ArrayList<SmsNumbers>();
          lstSmsNumbers.add(sms1);
          lstSmsNumbers.add(sms2);
          lstSmsNumbers.add(sms3);
          cl.setSmsNumbers(lstSmsNumbers);
     session.saveOrUpdate(cl);
     session.getTransaction().commit(); 
    session.close();    

并将其用作

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

我使用此参考来创建转换器 Json.NET, how to customize serialization to insert a JSON property