对于一个类中可能存在或可能不存在的字符串数组属性

对于一个类中可能存在或可能不存在的字符串数组属性

本文介绍了声明"Nullable< string> []"或"string []?"对于一个类中可能存在或可能不存在的字符串数组属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的JSON文件:

I have a JSON file like this:

[
  {
    "Id": 1,
    "Size": "big",
    "Order": 6
  },
  {
    "Id": 2,
    "Size": "small",
    "Order": 4
  },
  {
    "Id": 3,
    "Size": "medium",
    "Order": 2,
    "chips": []
  }
]

chips属性是一个数组,该数组可能会或可能不会出现在某些对象中(此刻当前为null).我应该这样声明json文件的类吗?

The chips property is an array that may or may not appear in some object (It is currently null at this point). Should I declare the class for the json file like this:

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

与?还是该属性像Nullable []这样的东西?

with the ? or something like Nullable[] for the property instead?

推荐答案

简而言之:在这种情况下,您根本不需要 Nullable< T> ?

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

string [] 是引用类型:

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

打印的输出将为 false .

因此,它可以是 null ,而无需任何修饰.

So, it can be null without any decoration.

返回您的示例.您还需要指定设置器,才能反序列化给定的json片段:

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; }
}

因为顶级实体不是对象,所以您需要使用 JArray 首先进行解析,然后通过 ToObject ( 1 ):

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[]>();

这篇关于声明"Nullable&lt; string&gt; []"或"string []?"对于一个类中可能存在或可能不存在的字符串数组属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:57