JSON(反序列化)将空值发送到列表

JSON (deserialized) sends null values to list

首先感谢您抽出宝贵的时间来看这篇文章。这是相当多的。 题: 我基本上是在尝试将 json 下载为字符串,然后将其反序列化为列表。之所以如此,我可以调用该列表的特定 属性(在我的例子中是 'ips',因为它是我真正需要的),如果满足要求,则将其插入 table。 问题是它将所有 null 值移动到数组中。 114 列 null 或空数组,我不知道为什么? 我想我会附加一个 link 到 JSON 因为它是一个巨大的文件它在这里 https://endpoints.office.com/endpoints/Worldwide?clientRequestId=b10c5ed1-bad1-445f-b386-b919946339a7

这是我的代码:

  1. JSON 的 getter 和 setter
       public class GetSetJsonIP {
       [JsonProperty("id")]
       public int id { get; set; }
    
       [JsonProperty("serviceArea")]
       public string ServiceArea { get; set; }
    
       [JsonProperty("serviceAreaDisplayName")]
       public string ServiceAreaDisplayName { get; set; }
    
       [JsonProperty("urls")]
       public IList<string> urls { get; set; }
    
       [JsonProperty("ips")]
       public IList<string> ips { get; set; }
    
       [JsonProperty("tcpPorts")]
       public string tcpPorts { get; set; }
    
       [JsonProperty("expressRoute")]
       public bool expressRoute { get; set; }
    
       [JsonProperty("category")]
       public string category { get; set; }
    
       [JsonProperty("required")]
       public bool required { get; set; }
    
       [JsonProperty("notes")]
       public string notes { get; set; }
    
       [JsonProperty("udpPorts")]
       public string udpPorts { get; set; }
       }
    
    
  2. 列表class
    public class ConvertJsonIP{
    public List<GetSetJsonIP> jsonIpConvert { get; set; }
    public List<GetSetJsonIP> jsonIPConvert = new List<GetSetJsonIP>();
    }

3.I 使用名为 o365IP

的空字符串下载 JSON
o365IP = wc.DownloadString(wc.BaseAddress + "/endpoints/Worldwide?clientRequestId=b10c5ed1-bad1-445f-b386-b919946339a7");
  1. 我使用我的列表反序列化为一个单独的 var
var o365IpVerion = JsonConvert.DeserializeObject<List<ConvertJsonIP>>(o365IP);

此代码未显示任何错误。所以我只能假设它是合乎逻辑的。应该注意的是,我不得不将

说真的,我已经在这上面停留了 3 天了,所以如果能提供任何帮助,我们将不胜感激!提前致谢!

您拥有的 json 是一个对象列表,其中每个对象都符合 GetSetJsonIp。您应该使用 List<GetSetJsonIP>

反序列化
var o365IpVerion = JsonConvert.DeserializeObject<List<GetSetJsonIP>>(o365IP);

public class GetJsonIP 工作正常。

你必须 DeserializeList<> 的原因是因为 json 对象以括号开头,使整个对象成为 Listarray .

var O365IpVersion = JsonConvert.DeserializeObject<List<GetJsonIP>(O365IP);

获取某个 属性 值的方法有多种。如果你只需要 ips 并想检查值然后更新它,那么你可以循环:

JArray arr = JArray.Parse(O365IP);
foreach (JObject obj in arr.Children<JObject>())
{
    foreach (JPRoperty prop in obj.Properties().Where(x => x.Name == "ips"))
    {
         //use prop.Value and perform tasks
    }
}

或者像这样简单地循环:

for (int i = 0; i < O365IpVersion.Count; i++)
{
    //use O365IpVersion.ElementAt(i).ips