Programing

Json Serialization에서 속성을 제외하는 방법

lottogame 2020. 4. 28. 08:15
반응형

Json Serialization에서 속성을 제외하는 방법


직렬화하는 DTO 클래스가 있습니다.

Json.Serialize(MyClass)

공공 재산을 어떻게 제외시킬 수 있습니까?

(어딘가에서 내 코드에서 사용하기 때문에 공개되어야합니다)


System.Web.Script.Serialization.NET 프레임 워크에서 사용 하는 ScriptIgnore경우 직렬화해서는 안되는 멤버에 속성을 넣을 수 있습니다 . 여기 에서 가져온 예를 참조 하십시오 .

다음과 같은 경우를 고려하십시오.

public class User {
    public int Id { get; set; }
    public string Name { get; set; }
    [ScriptIgnore]
    public bool IsComplete
    {
        get { return Id > 0 && !string.IsNullOrEmpty(Name); }
    } 
} 

이 경우 Id 및 Name 속성 만 직렬화되므로 결과 JSON 객체는 다음과 같습니다.

{ Id: 3, Name: 'Test User' }

추신. System.Web.Extensions이것이 작동 하도록 " "에 대한 참조를 추가하는 것을 잊지 마십시오


Json.Net 속성 [JsonIgnore]사용 하는 경우 직렬화 또는 역 직렬화하는 동안 필드 / 속성을 무시합니다.

public class Car
{
  // included in JSON
  public string Model { get; set; }
  public DateTime Year { get; set; }
  public List<string> Features { get; set; }

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

또는 DataContract 및 DataMember 특성을 사용하여 속성 / 필드를 선택적으로 직렬화 / 직렬화 할 수 있습니다.

[DataContract]
public class Computer
{
  // included in JSON
  [DataMember]
  public string Name { get; set; }
  [DataMember]
  public decimal SalePrice { get; set; }

  // ignored
  public string Manufacture { get; set; }
  public int StockCount { get; set; }
  public decimal WholeSalePrice { get; set; }
  public DateTime NextShipmentDate { get; set; }
}

자세한 내용은 http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size 를 참조하십시오.


당신은 사용할 수 있습니다 [ScriptIgnore]:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ScriptIgnore]
    public bool IsComplete
    {
        get { return Id > 0 && !string.IsNullOrEmpty(Name); }
    }
}

여기 참조

이 경우 ID와 이름은 일련 화됩니다.


내가 속성을 사용하여 코드를 장식 해야하는 것에 너무 열중하지 않는다면 컴파일 시간에 여기에서 일어날 일을 말할 수 없을 때 특히 내 솔루션입니다.

자바 스크립트 시리얼 라이저 사용

    public static class JsonSerializerExtensions
    {
        public static string ToJsonString(this object target,bool ignoreNulls = true)
        {
            var javaScriptSerializer = new JavaScriptSerializer();
            if(ignoreNulls)
            {
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
            }
            return javaScriptSerializer.Serialize(target);
        }

        public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
        {
            var javaScriptSerializer = new JavaScriptSerializer();
            foreach (var key in ignore.Keys)
            {
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
            }
            return javaScriptSerializer.Serialize(target);
        }
    }


public class PropertyExclusionConverter : JavaScriptConverter
    {
        private readonly List<string> propertiesToIgnore;
        private readonly Type type;
        private readonly bool ignoreNulls;

        public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
        {
            this.ignoreNulls = ignoreNulls;
            this.type = type;
            this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();
        }

        public PropertyExclusionConverter(Type type, bool ignoreNulls)
            : this(type, null, ignoreNulls){}

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            var result = new Dictionary<string, object>();
            if (obj == null)
            {
                return result;
            }
            var properties = obj.GetType().GetProperties();
            foreach (var propertyInfo in properties)
            {
                if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
                {
                    if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
                    {
                         continue;
                    }
                    result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
                }
            }
            return result;
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization
        }
    }

참고 URL : https://stackoverflow.com/questions/10169648/how-to-exclude-property-from-json-serialization

반응형