【问题标题】:Looping over long values from JSON and writing to console in C#从 JSON 循环长值并在 C# 中写入控制台
【发布时间】:2020-06-01 03:10:18
【问题描述】:

我在名为“Config.json”的文件中有一个类似结构的 JSON 文件:

    {
      "name": "Michael",
      "ids": [111111, 222222, 333333, 444444, 555555]
    }

我像这样反序列化它:

Config config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("Config.json"));

我有一个像这样的 Config 类:

class Config
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("ids")]
        public long Ids{ get; set; }
    }

如何遍历 id 并将它们写入控制台?我试过这个:

    var ids = new List<long> { config.Ids};

    foreach (long id in ids)
    {
        Console.WriteLine(id.ToString());
    }

但我得到一个错误:

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“System.Int64”,因为该类型需要 JSON 原始值(例如字符串、数字、布尔值、null)才能正确反序列化

我不知道如何反序列化和编写这个...我尝试过使用不同的值(uint64),但出现了同样的错误。

非常感谢!

【问题讨论】:

  • ids是一个数组,不能是一个long值,应该使用public long[] Ids

标签: c# .net json


【解决方案1】:

Json 中的 ids 属性是一个数组(如方括号所示)。要正确反序列化此 Json,您的模型类应如下所示

public class Config
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("ids")]
    public IEnumerable<long> Ids { get; set; }
}

然后,如果您想将所有值写入控制台

foreach (var id in config.Ids)
{
    Console.WriteLine(id); 
}

【讨论】:

    【解决方案2】:

    ids 是一个数组。

    public long Ids{ get; set; } 更改为public long[] Ids { get; set; } 并像这样打印它们:

        foreach (long id in config.Ids)
        {
            Console.WriteLine(id.ToString());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多