I am having an issue with the JSON DeserializeObject Method.
When My XML document has only one Branch
inside the Braches
node, I get an error because my class below says that the Branches is a List. I am unsure how to proceed with this because there could be ONE <Branch>
or multiple <Branch>
inside the <Branches>
.
Here's my Error Message:
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'PluginConsoleTestCode.Branch[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Openers.Opener[2].Branches.Branch.@id', line 1, position 689.
My Code Snippet:
// XML to JSON then JSON to RootObject
var json = JsonConvert.SerializeXmlNode(xmlDoc);
var response = JsonConvert.DeserializeObject<RootObject>(json);
Here's my XML:
<Openers>
<Opener Name="Name1" UserId="username">
<Branches>
<Branch id="103"></Branch>
<Branch id="104"></Branch>
<Branch id="105"></Branch>
<Branch id="106"></Branch>
<Branch id="107"></Branch>
<Branch id="108"></Branch>
</Branches>
</Opener>
<Opener Name="Name2" UserId="username">
<Branches>
<Branch id="109"></Branch>
<Branch id="110"></Branch>
<Branch id="111"></Branch>
<Branch id="112"></Branch>
</Branches>
</Opener>
<Opener Name="Name3" UserId="username">
<Branches>
<Branch id="113"></Branch>
</Branches>
</Opener>
</Openers>
XML Converted to JSON:
{
"Openers": {
"Opener": [
{
"@Name": "Name1",
"@UserId": "username",
"Branches": {
"Branch": [
{ "@id": "103" },
{ "@id": "104" },
{ "@id": "105" },
{ "@id": "106" },
{ "@id": "107" },
{ "@id": "108" }
]
}
},
{
"@Name": "Name2",
"@UserId": "username",
"Branches": {
"Branch": [
{ "@id": "109" },
{ "@id": "110" },
{ "@id": "111" },
{ "@id": "112" }
]
}
},
{
"@Name": "Name3",
"@UserId": "username",
"Branches": {
"Branch": { "@id": "113" }
}
}
]
}
}
Here is my Classes:
public class Branch
{
[JsonProperty("@id")]
public string Id { get; set; }
}
public class Branches
{
[JsonProperty("Branch")]
public List<Branch> Branch { get; set; }
}
public class Opener
{
[JsonProperty("@Name")]
public string Name { get; set; }
[JsonProperty("@UserId")]
public string UserId { get; set; }
public Branches Branches { get; set; }
}
public class Openers
{
public List<Opener> Opener { get; set; }
}
public class RootObject
{
public Openers Openers { get; set; }
}