2017-05-11 8 views
0

[ScriptIgnore] 속성을 가진 일부 속성이있는 객체를 직렬화하려고합니다. 그러나 때로는 JavaScriptSerializer에서 까지 해당 속성의 속성을 무시하지 않기를 원합니다. [ScriptIgnore] 속성에도 불구하고 전체 객체를 직렬화 할 수 있습니까?[ScriptIgnore] 속성으로 장식 된 속성을 직렬화하는 방법은 무엇입니까?

public static string ConvertToJson(this object objectToConvert) 
{ 
    var serializer = new JavaScriptSerializer(); 
    return serializer.Serialize(objectToConvert); 
} 

public static void ConvertFromJson(this object objectToConvert, string jsonString) 
{ 
    var serializer = new JavaScriptSerializer(); 
    object dummy = serializer.Deserialize(jsonString, objectToConvert.GetType()); 

    foreach(PropertyInfo property in objectToConvert.GetType().GetProperties()) 
     if(property.CanRead && property.CanWrite && property.GetCustomAttribute<ScriptIgnoreAttribute>() == null) 
      property.SetValue(objectToConvert, property.GetValue(dummy)); 
} 

답변

2

당신은 코딩과 JavaScriptConverter 객체를 제공하여 전체 직렬화 프로세스를 제어 할 수 있습니다

는 여기에 몇 가지 예제 코드입니다.

public class TestObject 
{ 
    [ScriptIgnore] 
    public string TestString { get; set; } 
} 

... 그리고 그것의 인스턴스를 직렬화 : 테스트를 위해

은 우리가 ScriptIgnore 속성들로 장식되어 하나의 속성이 간단한 클래스를 사용할 수 있도록

var serializer = new JavaScriptSerializer(); 
Console.WriteLine(serializer.Serialize(new TestObject { TestString = "test" })); 

속성은 물론 무시됩니다. 출력 :

{}

이제 우리는 JavaScriptConverter을 정의 할 수 있습니다.

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) 
{ 
    var testObject = obj as TestObject; 

    if (testObject != null) 
    { 
     // Create the representation. This is a simplified example. 
     Dictionary<string, object> result = new Dictionary<string, object>(); 
     result.Add("TestString", testObject.TestString);   
     return result; 
    } 

    return new Dictionary<string, object>(); 
} 

우리는 단순히 출력에 무시 속성을 추가 : 관련 부분은 여기 Serialize() 우리의 구현입니다. 그게 다야!

모든 것을 직렬화하려는 경우 변환기를 제공해야합니다. 변환기가 없으면 기본적으로 주석이 달린 속성은 무시됩니다.

사용법 :

serializer.RegisterConverters(new List<JavaScriptConverter> { new TestObjectConverter() }); 

출력 :

{ "TestString에": "테스트"}


전체 코드 덤프 :

void Main() 
{ 
    var serializer = new JavaScriptSerializer(); 
    Console.WriteLine(serializer.Serialize(new TestObject { TestString = "test" })); // prints: {} 
    serializer.RegisterConverters(new List<JavaScriptConverter> { new TestObjectConverter() }); 
    Console.WriteLine(serializer.Serialize(new TestObject { TestString = "test" })); // prints: {"TestString":"test"} 
} 

public class TestObject 
{ 
    [ScriptIgnore] 
    public string TestString { get; set; } 
} 

public class TestObjectConverter : JavaScriptConverter 
{ 
    private static readonly IEnumerable<Type> supportedTypes = new List<Type> { typeof(TestObject) }; 

    public override IEnumerable<Type> SupportedTypes => supportedTypes; 

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) 
    { 
     var testObject = obj as TestObject; 

     if (testObject != null) 
     { 
      // Create the representation. This is a simplified example. You can use reflection or hard code all properties to be written or do it any other way you like - up to you. 
      Dictionary<string, object> result = new Dictionary<string, object>(); 
      result.Add("TestString", testObject.TestString);   
      return result; 
     } 

     return new Dictionary<string, object>(); 
    } 
}