I am consuming some JSON in a C# console application and for some of the data, there is an array of options. Example JSON:
{
"FIELD_NAME": "Survey",
"VALUE": "",
"FIELD_ID": 1234,
"OPTIONS":[
{ "VALUE": "GENERAL", "DISPLAY_ORDER": 1, "DISPLAY": "GENERAL" },
{ "VALUE": "HPEFS", "DISPLAY_ORDER": 3, "DISPLAY": "HPEFS" },
{ "VALUE": "NONE", "DISPLAY_ORDER": 3, "DISPLAY": "NONE" }]
}
But sometimes for records in the JSON the OPTIONS is empty:
{"FIELD_NAME":"Product_Node3","VALUE":"","FIELD_ID":1740,"OPTIONS":{}}
As you can see the options is set to {} but it is my understanding that {} is an empty object, not an empty array.
When I try deserialize to a POCO I get an exception complaining that it requires a JSON array in the OPTIONS property.
My field class:
public class Field
{
public string FIELD_NAME { get; set; }
public string VALUE { get; set; }
public int FIELD_ID { get; set; }
public List<Option> OPTIONS { get; set;
}
}
And options class:
public class Option
{
public string VALUE { get; set; }
public int DISPLAY_ORDER { get; set; }
public string DISPLAY { get; set; }
}
The code which causes this exception is:
var stringTest = File.ReadAllText("json.txt");
var data = JsonConvert.DeserializeObject<List<Field>>(stringTest);
Exception is:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[testproj.Option]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.