다음과 같은 JSON이 있다고 가정합니다.
[{"$id": 1, Prop1: true, Prop2: {"$id": 2, Prop2: {"$id": 3, SomeProp: true}}}, {"$ref" : 3}]
그리고 JsonConvert.DeserializeObject (aboveJson)를 사용합니다. 이것이 deserialize되는지 어떻게 확인할 수 있습니까?
[{Prop1: true}, {SomeProp: true}] //[0] = id1, [1] = id3
대신 :
[{Prop1: true}, null] //[0] = id1, [1] = null because it doesn't match on "$ref" down the hierarchy.
명확성을 위해 편집 :이 코드를 실행하면 어떻게 되나요?
public class StackOverflow
{
public bool Prop1 { get; set; }
}
static void Main(string[] args)
{
string json = @"[{""$id"": ""1"", Prop1: true, Prop2: {""$id"": ""2"", Prop2: {""$id"": ""3"", Prop1: true}}}, {""$ref"" : ""3""}]";
dynamic result = JsonConvert.DeserializeObject<List<StackOverflow>>(json);
}
result [0]은 StackOverflow 클래스입니다. result [1]이 null입니다. 역 참조하려면 어떻게해야합니까? 내가 무엇을 놓치고 있습니까?
"ref"
및 "$id"
기준 추적 및 보존이 활성화되면 특성 Json.NET으로 삽입된다. 설명서는 객체 참조 보존을 참조하십시오 . 따라서 원래 개체 그래프를 역 직렬화하려면 설정을 JsonSerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects
사용해야합니다.
그러나이 설정이 활성화 된 경우에도 제안 된 데이터 모델이 JSON과 일치하지 않습니다. 형식이 지정된 JSON은 다음과 같습니다.
[
{
"$id": "1",
"Prop1": true,
"Prop2": {
"$id": "2",
"Prop2": {
"$id": "3",
"Prop1": true
}
}
},
{
"$ref": "3"
}
]
보시다시피 배열의 첫 번째 항목에는 두 개의 속성이 있으며 그 중 하나는 다른 내부 중첩 개체가있는 중첩 개체입니다. 배열의 두 번째 항목은 첫 번째 항목에서 가장 안쪽에있는 중첩 개체에 대한 참조입니다. 중첩 된 참조로 List<StackOverflow>
인해 다음과 같이 플랫으로 역 직렬화 할 수 없습니다 .
public class StackOverflow
{
public bool Prop1 { get; set; }
}
대신 다음과 같은 재귀 모델을 정의해야합니다.
public class StackOverflow
{
public bool? Prop1 { get; set; }
public StackOverflow Prop2 { get; set; }
}
그러면 deserialization 코드는 다음과 같습니다.
string json = @"[{""$id"": ""1"", Prop1: true, Prop2: {""$id"": ""2"", Prop2: {""$id"": ""3"", Prop1: true}}}, {""$ref"" : ""3""}]";
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var result = JsonConvert.DeserializeObject<StackOverflow []>(json, settings);
샘플 바이올린 .
이제 다음과 같이 다시 직렬화 하지 않으면PreserveReferencesHandling.Objects
:
var settingsOut = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
var jsonWithoutRef = JsonConvert.SerializeObject(root, settingsOut);
Console.WriteLine("Re-serialized with PreserveReferencesHandling.None");
Console.WriteLine(jsonWithoutRef);
의 가장 안쪽 인스턴스 StackOverflow
가 두 번째 배열 위치에 올바르게 배치 되었음을 알 수 있습니다.
[
{
"Prop1": true,
"Prop2": {
"Prop2": {
"Prop1": true
}
}
},
{
"Prop1": true
}
]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다