APALALA
APALALA

Reputation: 60

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 ?

Upvotes: 1

Views: 752

Answers (2)

Rizvi Sarwar
Rizvi Sarwar

Reputation: 26

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

Upvotes: 1

Marcio Rinaldi
Marcio Rinaldi

Reputation: 3513

You can do a foreach loop:

foreach(var item in data) {
    Console.WriteLine(item.UserId);
}

Upvotes: 2

Related Questions