1 | initial version |
The process of converting a JSON array into a C# class instance with type safety involves the following steps:
Define a C# class that represents the JSON object.
Use a JSON serializer to deserialize the JSON array into an instance of the C# class.
Ensure that the deserialization process is type-safe by specifying the type of the expected object.
Access the properties of the C# class instance to work with the data from the deserialized JSON array.
Here is an example of how to perform this conversion:
// Define a class that represents the JSON data
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// Deserialize the JSON array into an instance of the Person class
string json = "[{ \"Name\":\"John\", \"Age\":30 },{ \"Name\":\"Jane\", \"Age\":25 }]";
List<Person> people = JsonSerializer.Deserialize<List<Person>>(json);
// Access the properties of the Person objects
foreach (Person p in people)
{
Console.WriteLine($"Name: {p.Name}, Age: {p.Age}");
}
In this example, we define a Person
class with Name
and Age
properties. We then use the JsonSerializer.Deserialize
method to deserialize a JSON array into a List<Person>
instance. By specifying the type of the expected object (List<Person>
), this process is type-safe.
Finally, we can access the properties of the Person
objects in the people
list to work with the data from the deserialized JSON array.