I have a list of objects (A), each object containing a list of objects (B). I did the serialization of the list of As without problems but when I did the deserialization of As the list of Bs inside of each A, has twice the original quantity of Bs. Why is this happening?
var sample = new List<A>
{
new A
{
Flag = true,
Amount = 10,
Bs = new List<B>
{
new B {Amount = 4, Id = Guid.NewGuid()},
new B {Amount = 6, Id = Guid.NewGuid()}
}
},
new A
{
Flag = true,
Amount = 20,
Bs = new List<B>
{
new B {Amount = 4, Id = Guid.NewGuid()},
new B {Amount = 6, Id = Guid.NewGuid()}
}
},
new A
{
Flag = false,
Amount = 30,
Bs = new List<B>
{
new B {Amount = 4, Id = Guid.NewGuid()},
new B {Amount = 6, Id = Guid.NewGuid()}
}
}
};
var serialized = JsonConvert.SerializeObject(sample, ContractResolver.AllMembersSettings);
var deserialized = JsonConvert.DeserializeObject<List<A>>(serialized, ContractResolver.AllMembersSettings);
class A
{
public bool Flag { get; set; }
public decimal Amount { get; set; }
public List<B> Bs { get; set; }
}
class B
{
public Guid Id { get; set; }
public decimal Amount { get; set; }
}
public class ContractResolver : DefaultContractResolver
{
public static readonly JsonSerializerSettings AllMembersSettings =
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
ContractResolver = new ContractResolver()
};
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var props =
type
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite)
.Select(p => base.CreateProperty(p, memberSerialization))
.Union(
type
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Select(f => base.CreateProperty(f, memberSerialization)))
.ToList();
props.ForEach(p => { p.Writable = true; p.Readable = true; });
return props;
}
}