简体   繁体   中英

C# Access value from serialized json array

I have a simple serialized json array

string json = "[{\"id\":100,\"UserId\":99},{\"id\":101,\"UserId\":98}]";
var data = (List<Model>)Newtonsoft.Json.JsonConvert.DeserializeObject(json , typeof(List<Model>));

my model to deserialize:

public class Model 
{ 
    public int? id { get; set; }
    public int? UserId { get; set; }
}

What is the best way to retrieve data from each Index[?] and print it to Console ?

You can do a foreach loop:

foreach(var item in data) {
    Console.WriteLine(item.UserId);
}
 string json = "[{\"id\":100,\"UserId\":99},{\"id\":101,\"UserId\":98}]";
        var objects = JArray.Parse(json);
        var firstIndexValue = objects[0];
        Console.WriteLine(firstIndexValue);

        foreach (var index in objects)
        {
            Console.WriteLine(index);
        }
for (int index = 0; index < objects.Count; index++)
        {
            Console.WriteLine(objects[index]);
        }

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