I'm using .NET Framework 4.7.2 with the package Newtonsoft.Json 12.0.3.
I'm trying to de-serialize an incoming JSON string into a List<Person>. When the JSON string is an array of random objects, the result is actually a List<Person> of the same length as the incoming array and each Person seems to have been created with the default constructor!
public class Person
{
public string Name { get; set; }
public int? Age { get; set; }
}
De-serialization example:
string json = "[{\"random\": \"stuff\"}, {\"whatever\": 24}]";
var persons = JsonConvert.DeserializeObject<List<Person>>(json);
persons is a list with 2 Person objects that have both Name null and Age null. This seems like really strange default behavior!
I want to throw an error if the incoming array has even a single object that isn't a proper Person. I wan them explicitly to have a Name and an Age, even if they're null. Example: I want "[{"Name": "Bob", "Age":null}]" to become a Person with Name="Bob" and Age equals null. I only care that they explicitly define all the properties.
How can this be done without changing the Person class?
UPDATE: For future reference, the linked questions cover my needs because I want to do both of these things at the same time.