Problem
When trying to deserialize some Json using Newtonsoft's Json.NET nuget library my collection-properties are null when I do NOT provide a JsonSerializerSettings
- why?
Details
I have some valid json data and deserializing it into my custom class / POCO. Now, all the simple properties (like string
s, int
's, etc) all get set correctly. My simple child classes also get set properly (eg. a User
property or a BuildingDetails
property, etc).
All my collections are null
, though. The setters are never called (I've put a break point in there and they don't get set, but the others do get called/set).
eg. property.
List<Media> Images { get { ... } set { ... } }
eg.
var foo = new Foo();
var json = JsonConvert.Serialize(foo);
var anotherFoo = JsonConvert.Deserialize<Foo>(json);
// the collection properties on anotherFoo are null
Now - this is the crazy thing: when I use a JsonSerializerSettings
it now works:
// NOTE: ModifiedDataContractResolver <-- skips any property that is a type
/ ModifiedData (which is a simple custom class I have).
var settings = new JsonSerializerSettings
{
ContractResolver = new ModifiedDataContractResolver(),
ObjectCreationHandling = ObjectCreationHandling.Replace,
Formatting = Formatting.Indented
};
var foo = new Foo();
var json = JsonConvert.Serialize(foo, settings);
var anotherFoo = JsonConvert.Deserialize<Foo>(json, settings);
my collections are now set!
Take note of this: ObjectCreationHandling = ObjectCreationHandling.Replace
. This is the magical setting that makes things work.
What is this doing and why does not having this setting mean my collections are not getting set/created/etc?
Another clue. If I do not have the setter, collection is null / not set. If I have the setter like this, it fails too:
public List<Media> Images
{
get { return new List<Media> { new Media{..}, new Media{..} }; }
set { AddImages(value); }
}
If I do NOT return the list, in the getter
the collection is SET! IT WORKS!
private List<Media> _images;
public List<Media> Images
{
get { return _images; }
set { AddImages(value); }
}
Notice how it's now just using a baking field instead?
It's like there's some weird connection/correlation between the collection's GETTER property and result and how Json.net sets this data using the auto
setting?