[英]Declare "Nullable<string>[]" or "string[]?" for string array property that may or may not exist inside a class?
I have a JSON file like this:我有一个这样的 JSON 文件:
[
{
"Id": 1,
"Size": "big",
"Order": 6
},
{
"Id": 2,
"Size": "small",
"Order": 4
},
{
"Id": 3,
"Size": "medium",
"Order": 2,
"chips": []
}
]
The chips property is an array that may or may not appear in some object (It is currently null at this point). chips属性是一个数组,可能会出现也可能不会出现在一些object中(目前是null)。 Should I declare the class for the json file like this:我是否应该像这样为 json 文件声明 class:
public class Settings
{
public int Id { get;}
public string Size { get;}
public int Order { get;}
public string[]? Chips { get;}
}
with the?与? or something like Nullable[] for the property instead?或类似 Nullable[] 的属性?
In short: you don't need Nullable<T>
or ?
简而言之:您不需要Nullable<T>
或?
in this case at all.在这种情况下。
string[]
is reference type: string[]
是引用类型:
Console.WriteLine(typeof(string[]).IsValueType);
the printed output will be false
.打印的 output 将是false
。
So, it can be null
without any decoration.因此,它可以是null
,无需任何修饰。
Back to your sample.回到你的样本。 You need to specify setters as well to be able deserialize the given json fragement:您还需要指定 setter 才能反序列化给定的 json 片段:
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 ):因为顶级实体不是 object,所以您需要先使用JArray解析它,然后通过ToObject
( 1 ) 将其转换为Settings
:
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[]>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.