당신은 코딩과 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>();
}
}