2016-09-07 3 views
0

JSON을 사용하는 C# 응용 프로그램이 있습니다. 버그가 있으며 약간 복잡하기 때문에 예제를 드리겠습니다. 우리는이 클래스가있는 경우 : JSON 객체 FatherObj, SonObj가 중복됩니다 개체의 손자의 목록을 직렬화 복원 할 때 다음기본 변환기를 사용하는 사용자 지정 Json 변환기

public class FatherObj 
{ 
    public SonObj Son {get; set;} 
} 

public class SonObj 
{ 
    public List<GrandChildObj> GrandChildren {get; set;} 
} 

. 나는리스트의 선언 위에 다음 코드를 추가하여 고정 : 나는 전체 응용 프로그램의 JSON 직렬화 설정에 추가하려 할 때

[JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Replace)] 

그러나,이 문제를 일으켰습니다. 그래서 List 객체에만 적용 할 JsonConverter를 만들기로 결정했다. 그리고 deserialize 할 때 반환하기 전에 Distinct 메서드를 호출 할 것이다. 그러나 JsonConverter는 추상 클래스이므로 메서드를 구현할 때 기본 메서드를 호출 할 수 없습니다 (추상적이기 때문에). 기본 변환기 설정은 어떻게 호출합니까? 나는 별개의 것 외에 다른 변환을 창조하고 싶지 않다.

+0

윌'[이 질문]에서 CollectionClearingContractResolver' (https://stackoverflow.com/questions/35482896/clear-collections-before-adding-items-when- : 그 다음 코드) DefaultContractResolver에서 상속 populating-existing-objects)이 필요를 충족합니까? – dbc

+0

"PopulateObject"를 호출하는 코드의 위치가 없습니다. 이 기능은 비 직렬화에 대해서만 계속 사용할 수 있습니까? –

+0

해야합니다. 당신은'JsonSerializerSettings.ContractResolver'를 설정하고 그 설정을'DeserializeObject'에 전달할 수 있습니다. http://www.newtonsoft.com/json/help/html/contractresolver.htm을 참조하십시오. 하지만 작동하지 않거나 다른 문제가 발생하면 작동하지 않는 C# 코드를 공유 할 수 있습니까? – dbc

답변

1

좋아, 그래서 사용자 DBC의 도움으로 검색을 조금 후 - 나는 그의 대답을했다하지만 다른 링크에서 : How to apply ObjectCreationHandling.Replace to selected properties when deserializing JSON?

그가 링크에 게시 솔루션 : 사용자 정의 ContractResolver 만들기 (

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) 
{ 
    var jsonProperty = base.CreateProperty(member, memberSerialization); 
    if (jsonProperty.ObjectCreationHandling == null && jsonProperty.PropertyType.GetListType() != null) 
     jsonProperty.ObjectCreationHandling = ObjectCreationHandling.Replace; 
    return jsonProperty; 
} 

public static class TypeExtensions 
{ 
    public static Type GetListType(this Type type) 
    { 
     while (type != null) 
     { 
      if (type.IsGenericType) 
      { 
       var genType = type.GetGenericTypeDefinition(); 
       if (genType == typeof(List<>)) 
        return type.GetGenericArguments()[0]; 
      } 
      type = type.BaseType; 
     } 
     return null; 
    } 
} 
관련 문제