Page
개체를 serialize 할 때 Json.Net은 해당 컨트롤을 serialize 할 때 IList
인 컨트롤에 $ type 속성을 추가하지 않습니다. 내 코드 생성자와 내 WebAPI 시작 프로그램에 다음 코드를 추가하려고 시도했지만 Json.Net은 여전히 $ type 정보를 Control
에 추가하지 않고 직렬화합니다.
JsonConvert.DefaultSettings =() => new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
};
는 테스트를 위해, 나는 JSON 코드에서 컨트롤에 자신을
$type
속성을 추가하고, Json.Net는
직렬화 제대로 개체 수 있었다,하지만 여전히 제대로 직렬화되지 않습니다. 수업 내용은 다음과 같습니다. 여기
public class Page {
public Guid Id { get; set; }
public Guid CustomerId { get; set; }
public IList<Control> Controls { get; set; }
}
그리고
은 컨트롤 클래스입니다 :public class Control : ControlBase
{
public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.Base; } }
}
그리고 여기 ControlBase 추상 클래스입니다 :
public abstract class ControlBase
{
public Guid Id { get; set; }
public virtual Enums.CsControlType CsControlType { get; }
public Enums.ControlType Type { get; set; }
public string PropertyName { get; set; }
public IList<int> Width { get; set; }
public string FriendlyName { get; set; }
public string Description { get; set; }
}
그리고 여기 Control에서 파생 된 OptionsControl입니다 :
public class OptionsControl : Control
{
public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.OptionsControl; } }
public IDictionary<string, string> Options;
}
그리고이 json으로 나오는 방법이다 : 당신이 볼 수 있듯이, Json.Net는 JSON 객체에 $type
속성을 추가하지 않은
"Pages": [
{
"Id": "00000000-0000-0000-0000-000000000000",
"CustomerId": "00000000-0000-0000-0000-000000000000",
"Controls": [
{
"Options": {
"TN": "TN"
},
"CsControlType": 4,
"Id": "00000000-0000-0000-0000-000000000000",
"Type": 4,
"PropertyName": "addresses[0].state",
"Width": [
2,
2,
6
],
"FriendlyName": "State",
"Description": null
}
]
}
]
. 문제는 때로는베이스 Control
개체를 제공하기 위해 Json.Net이 필요하지만 때로는 Control
에서 상속받은 OptionsControl
개체의 인스턴스를 제공해야 할 필요가 있다는 것입니다. Json.Net이 내 컨트롤에 $ type 속성을 추가하지 않는 이유는 무엇입니까?
''Type ": 4,''$ type' '과 다른 점은 어디에서 어떻게 참조 할'$ type'입니까? 좀 더 명확하게 "원하는"출력을 추가 할 수 있습니까? 나는 똑같은 것을 보지 않을 수도 있습니다 ... –
코드가 독립형 직렬화에 잘 작동합니다 (https://dotnetfiddle.net/gKetpA 참조). 따라서 직렬화 할 웹 API와 같은 프레임 워크를 사용해야합니다. 어떤 프레임 워크를 사용하고 있습니까? 예를 들어 MVC 4 웹 API의 경우 [MVC 4 Web API에서 Json.NET에 대한 사용자 정의 JsonSerializerSettings 설정 방법] (https://stackoverflow.com/q/13274625/3744182)을 참조하십시오. 또는 목록 속성에'[JsonProperty (ItemTypeNameHandling = TypeNameHandling.Auto)]'를 추가 할 수 있습니다. – dbc
@dbc .NET Core WebAPI를 사용하고 있습니다. 내 질문이 해당 코드로 업데이트되었습니다. 목록에 [JsonProperty (ItemTypeNameHandling = TypeNameHandling.Auto)]'를 추가하려고 시도했지만 일반 목록에는'$ type'이 있지만 목록에는 컨트롤에는 없습니다. – Targaryen