내 목표는 속성이없는 속성과 특정 사용자 지정 속성이있는 속성을 직렬화하는 것입니다.
다음 클래스의 경우 :
public class Msg
{
public long Id { get; set; }
[CustomAttributeA]
public string Text { get; set; }
[CustomAttributeB]
public string Status { get; set; }
}
메서드를 호출 할 때 Serialize(object, CustomAttributeA)
다음 출력을 원합니다.
{
"Id" : someId,
"Text" : "some text"
}
을 (를) 전화 Serialize(object, CustomAttributeB)
하면 다음 항목을 원합니다.
{
"Id" : someId,
"Status" : "some status"
}
커스텀을 생성하여이를 달성 할 수 있다는 것을 읽었 ContractResolver
지만이 경우 두 개의 개별 계약 해결자를 생성해야합니까?
목표를 달성하기 위해 두 개의 개별 리졸버가 필요하지 않습니다. ContractResolver
유형 매개 변수가 직렬화 할 때 찾고있는 속성을 나타내는 사용자 정의 제네릭을 만드십시오 .
예를 들면 :
public class CustomResolver<T> : DefaultContractResolver where T : Attribute
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in list)
{
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null)
{
// if the property has any attribute other than
// the specific one we are seeking, don't serialize it
if (pi.GetCustomAttributes().Any() &&
pi.GetCustomAttribute<T>() == null)
{
prop.ShouldSerialize = obj => false;
}
}
}
return list;
}
}
그런 다음 도우미 메서드를 만들어 확인자를 만들고 개체를 직렬화 할 수 있습니다.
public static string Serialize<T>(object obj) where T : Attribute
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver<T>(),
Formatting = Formatting.Indented
};
return JsonConvert.SerializeObject(obj, settings);
}
직렬화하려면 다음과 같이 도우미를 호출하십시오.
string json = Serialize<CustomAttributeA>(msg);
데모 바이올린 : https://dotnetfiddle.net/bRHbLy
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다