I have the following JSON (I can't change the incoming JSON as it is from a 3rd party system):
{
"id": 23,
"userName":"test@test.com",
"tags":
{
"Employee ID":
{
"name":"Employee ID",
"value":"123456789"
},
"Job Family":
{
"name": "Job Family",
"value": "Accounting and Finance"
}
}
}
First, I tried to deserialize using this class structure:
public class User
{
[JsonProperty("id")]
public int ID { get; set; }
[JsonProperty("username")]
public string Email { get; set; }
[JsonProperty("tags")]
public TagsJson Tags { get; set; }
}
public class TagsJson
{
[JsonProperty("tags")]
public List<Tag> Tags { get; set; }
}
public class Tag
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
In using Newtonsoft's JsonConvert.DeserializeObject(json);
, the User.Tags property is always empty. This is obviously because there are no "Tags" under the "Tags" attribute.
Yet, if I change the User class as follows...
public class User
{
[JsonProperty("id")]
public int ID { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("tags")]
public List<Tag> Tags { get; set; }
// I even tried Tag[] instead of List<Tag> here
}
...I get the following error:
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Tag]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Any suggestions on creating the User class to allow it to deserialize correctly would be greatly appreciated.
EDIT
So this may or may not be the best answer, but it works. The tags coming in will be one of a dozen different names. So I created a Tags class with a property for each of the 12 possibilites. Since none are required, any of them that do appear will get populated. Here's my adjusted User, Tags (formerly TagsJson) and Tag classes below - but I'm definitely interested in a better solution.
public class User
{
[JsonProperty("id")]
public int ID { get; set; }
[JsonProperty("username")]
public string Email { get; set; }
[JsonProperty("tags")]
public Tags AllTags { get; set; }
}
public class Tags
{
[JsonProperty("Employee ID")]
public Tag EmployeeID { get; set; }
[JsonProperty("Job Family")]
public Tag JobFamily { get; set; }
// ... and 10 more properties for additional tags that may appear but are not required
}
public class Tag
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
The suggested answer of this question does not work in my case because the JSON is not an array or a collection but a list of unique attribute names with a name/value pairing.