简体   繁体   中英

Looping over long values from JSON and writing to console in C#

I have a JSON file structured like so in a file named 'Config.json':

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

I am deserializing it like so:

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

I have a Config class like so:

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

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

How do I iterate over the ids and write them to console? I have tried this:

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

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

But I get an error:

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Int64' because the type requires a JSON primitive value (eg string, number, boolean, null) to deserialize correctly

I cannot figure out how to deserialize and write this...I have tried experimenting with different values (uint64) but the same error occurs.

Thanks so much!

ids is an array.

Change public long Ids{ get; set; } public long Ids{ get; set; } public long Ids{ get; set; } to public long[] Ids { get; set; } public long[] Ids { get; set; } public long[] Ids { get; set; } and print them like this:

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

Your ids property in your Json is an array (as indicated by the square brackets). To properly desierialize this Json, your model class should look like

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

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

Then, if you want to write all of the values to console

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM