Created
August 18, 2020 16:39
-
-
Save layomia/2d6a1b6db6356303d3351848bf994ff8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text.Json; | |
using System.Text.Json.Serialization; | |
namespace RefHandlingDemo | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var janeEmployee = new Employee | |
{ | |
Name = "Jane Doe" | |
}; | |
var johnEmployee = new Employee | |
{ | |
Name = "John Smith" | |
}; | |
janeEmployee.Reports = new List<Employee> { johnEmployee }; | |
johnEmployee.Manager = janeEmployee; | |
var options = new JsonSerializerOptions | |
{ | |
ReferenceHandler = ReferenceHandler.Preserve | |
}; | |
string serialized = JsonSerializer.Serialize(janeEmployee, options); | |
Console.WriteLine(serialized); | |
Employee janeDeserialized = JsonSerializer.Deserialize<Employee>(serialized, options); | |
Console.WriteLine(janeDeserialized.Reports[0].Manager == janeDeserialized); | |
} | |
} | |
class Employee | |
{ | |
public string Name { get; set; } | |
public Employee Manager { get; set; } | |
public List<Employee> Reports { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment