CSharp · Console
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
A a = new A();
a.Str1 = "foo";
a.Bs = new List<B>();
a.Bs.Add(new B(a));
a.Bs.Add(new B(a));
a.Bs.Add(new B(a));
JsonSerializerSettings settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Formatting = Formatting.Indented
};
Console.WriteLine("---- serialize ----");
var json = JsonConvert.SerializeObject(a, settings);
Console.WriteLine(json);
Console.WriteLine("---- deserialize ----");
var newA = JsonConvert.DeserializeObject<A>(json, settings);
}
}
public class A
{
public string Str1 { get; set; }
public IList<B> Bs { get; set; }
}
public class B
{
[JsonProperty]
private A a;
public B(A a)
{
this.a = a;
Console.WriteLine(a != null ? a.Str1 : "a is null");
}
}