다음 시나리오 (Newtonsoft.Json)가 있습니다.
public class SubElement
{
[JsonConstructor]
public SubElement(string name, Element parent)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("message", nameof(name));
}
Name = name;
Parent = parent ?? throw new ArgumentNullException(nameof(parent));
}
public string Name { get;private set; }
public Element Parent { get; }
}
[JsonObject(IsReference =true)]
public class Element
{
[JsonConstructor]
public Element(string name, IList<SubElement> subelements)
{
Name = name;
Subelements = subelements;
}
public string Name { get; set; }
public IList<SubElement> Subelements { get; }
}
Element element = new Element("test", new List<SubElement>());
element.Subelements.Add(new SubElement("first", element));
element.Subelements.Add(new SubElement("second", element));
string serialized = JsonConvert.SerializeObject(element);
Console.WriteLine(serialized);
Element deserialized = JsonConvert.DeserializeObject<Element>(serialized);
deserialization 프로세스에서 SubElement 생성자 는 직렬화 된 데이터에서 제대로 저장되지만 부모 요소 가 null 인 상태로 ivok 됩니다. 순환 참조를 관리하기 위해 [JsonObject (IsReference = true)] 속성을 사용했지만 역 직렬화가 작동하는 데 충분하지 않은 것 같습니다.
부모에 대한 참조를 포함하는 트리와 유사한 구조를 직렬화 / 역 직렬화하려고합니다.
문제는 [JsonConstructor]
아이들을 부를 때 부모가 아직 건설되지 않았다는 것입니다. 그러나 속성을 deserialize하는 경우에는 중요하지 않습니다 (이 경우 매개 변수없는 생성자가 필요합니다).
[JsonObject(IsReference = true)]
public class Element
{
[JsonProperty] // required for private setter
public string Name { get; private set; }
[JsonProperty]
public IList<SubElement> Ports { get; private set; }
[JsonConstructor] // required for private constructor
Element() { }
... // your public constructors (not used for serialization)
}
public class SubElement
{
[JsonProperty]
public string Name { get; private set; }
[JsonProperty]
public Element Parent { get; private set; }
[JsonConstructor]
SubElement() { }
...
}
나는 당신의 아키텍처를 유지하려고 노력했습니다. 사용 참고 문헌 : 개인 세터를 역 직렬화 , 개인 생성자를 역 직렬화 .
json은 동일하게 보입니다.
{ "$ id": "1", "Name": "test", "Ports": [{ "Name": "first", "Parent": { "$ ref": "1"}}, { " 이름 ":"second ","Parent ": {"$ ref ":"1 "}}]}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다