[Solved] Declare “Nullable[]” or “string[]?” for string array property that may or may not exist inside a class?


In short: you don’t need Nullable<T> or ? in this case at all.

string[] is reference type:

Console.WriteLine(typeof(string[]).IsValueType);

the printed output will be false.

So, it can be null without any decoration.


Back to your sample. You need to specify setters as well to be able deserialize the given json fragement:

public class Settings
{
    public int Id { get; set; }
    public string Size { get; set; }
    public int Order { get; set; }
    public string[] Chips { get; set; }
}

Because the top-level entity is not an object that’s why you need to use JArray to parse it first and then convert it to Settings via the ToObject (1):

var json = "[\r\n  {\r\n    \"Id\": 1,\r\n    \"Size\": \"big\",\r\n    \"Order\": 6\r\n  },\r\n  {\r\n    \"Id\": 2,\r\n    \"Size\": \"small\",\r\n    \"Order\": 4\r\n  },\r\n  {\r\n    \"Id\": 3,\r\n    \"Size\": \"medium\",\r\n    \"Order\": 2,\r\n    \"chips\": []\r\n  }\r\n]";
var semiParsedData = JArray.Parse(json);
var settings = semiParsedData.ToObject<Settings[]>();

solved Declare “Nullable[]” or “string[]?” for string array property that may or may not exist inside a class?