【问题标题】:Ignore c# fields dynamically from Json Serialize从 Json Serialize 中动态忽略 c# 字段
【发布时间】:2015-11-16 10:15:58
【问题描述】:

出于 API 目的,我需要根据收到的标准忽略一些字段。通常我可以使用[ScriptIgnore] 属性来做到这一点。

但我如何才能动态地忽略字段(基于某些条件)?

【问题讨论】:

    标签: c# json asp.net-web-api


    【解决方案1】:

    使用 Newtonsoft.Json 包中的 JsonIgnore 属性。

    那么,如果您希望它是动态条件的,请参阅ShouldSerialize

    【讨论】:

      【解决方案2】:

      假设您使用Json.Net,您可以通过创建一个继承自JsonConverter 的类来为特定类型创建自己的转换器。

      public class MyJsonConverter : JsonConverter
      {
          public override bool CanConvert(Type objectType)
          {
              return objectType == typeof(MyType);
          }
      
          public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
          {
              throw new NotImplementedException();
          }
      
          public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
          {
              var objectToSerialize = new {}; //create the object you want to serialize here, based on your dynamic conditions
              new JsonSerializer().Serialize(writer, objectToSerialize); //serialize the object to the current writer
          }
      }
      

      然后您调用JsonConvert.DeserializeObject 并将您的自定义转换器传递给它:

      JsonConvert.DeserializeObject<MyType>(jsonString, new MyJsonConverter());
      

      【讨论】:

        猜你喜欢
        • 2020-01-16
        • 1970-01-01
        • 2014-05-30
        • 2016-02-16
        • 2013-03-24
        • 2015-02-23
        • 1970-01-01
        • 1970-01-01
        • 2014-06-20
        相关资源
        最近更新 更多