I have a following JSON string:
{
"items" : "1",
"itemdetails":
[
{
"id" : "5",
"name:" "something"
}
]
}
items represents item count and actual items are in itemdetails.
I would like to deserialize this to a class like this:
class Parent
{
JsonProperty("itemdetails")]
public IEnumerable<Item> Items { get; set; }
}
class Item
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name {get; set; }
}
However, when I call
JsonConvert.DeserializeObject<Parent>(inputString)
I get a JsonSerializationException that string "1" cannot be converted to IEnumerable<Item>. I guess the parser is trying to deserialize items from JSON into Items property because they match by name. And it's ignoring the JsonProperty attribute.
Is this by design? Any workarounds? Thanks!
EDIT
As Brian Rogers commented, this code as it is works correctly. I figured that I missed to add a piece of the puzzle.
The problem is if I want to use private collection setters and initialize those properties from the constructor.
public Parent(IEnumerable<Item> items)
{
this.Items = items;
}
This is causing the exception to be thrown. What should I do here? Annotate constructor arguments somehow? Or use ConstructorHandling.AllowNonPublicDefaultConstructor?