I am trying to deserialize JSON by reading a file. This file will be the same as what I will receive in future requests. I created classes based on some sample data. However, I am running into trouble with property names that do not appear on every response. Therefore, I receive an exception which says
"ArgumentException: Could not cast or convert from System.String to object" error.
For example, below is a sample of the JSON I am trying to deserialize. My classes are build for this layout
"contents": [
{
"template": "paragraph",
"title": null,
"values": [
{
"name": null,
"value": "paragraph of text"
},
{
"name": null,
"value": "paragraph of text"
}
]
}
]
However sometimes I get this as a response.
"contents": [
{
"template": "paragraph",
"title": null,
"values": [
"paragraph of text"
]
}
]
Notice how the { } and properties "name" and "value" are gone from the "values" array?
Here is my class for the "contents" array
public class Contents
{
public Contents()
{
Values = new List<TemplateValue>();
}
[JsonPropertyName("template")]
public string Template { get; set; }
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("values")]
public List<TemplateValue> Values { get; set; }
}
public class TemplateValue
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("value")]
public string Value { get; set; }
}
Here is how I am deserializing the file
var jsonString = File.ReadAllText(_jsonFilelocation);
var jsonObject = JsonConvert.DeserializeObject<Contents>(jsonString);
How can I adjust my code to fix this type of scenario? Thanks in advance for any help!