I have dynamic nested JSON coming from front-end. See the below, as dynamic as only those keys whose value ain't null are sent. In these case, middle initial isn't been filled, so you don't find it:
{
"name": {
"firstname": "fst",
"lastname": "lst"
},
"gender": "male",
"birthdate": "2021-02-09",
"maritalstatus": "Never married",
"id": {
"social": "123456789"
}
}
I've tried these for each potential properties:
JsonElement lastname;
question1.TryGetProperty("lastname", out lastname);
But looking for a more decent way, for example the below one:
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true
};
var jsonModel = JsonSerializer.Deserialize<Survey>(obj, options);
var modelJson = JsonSerializer.Serialize(jsonModel, options);
But the problem is this way only can deal with the first-level properties, like gender, birthdate, maritalstatus, but invalid with firstname, lastname and social.
How to solve it or any other approaches I can try, many thanks!
UPDATE1:
Survey is a poco looks like this but much more than this properties, see those annotations, I'm trying to let itself do the mapping instead of on my own:
public class Survey
{
[JsonPropertyName("firstname")]
public string FirstName{get;set;}
[JsonPropertyName("middleinitial")]
public char MiddleInitial{get;set;}
[JsonPropertyName("lastname")]
public string LastName{get;set;}
[JsonPropertyName("jrsr")]
public string JrSr{get;set;}
[JsonPropertyName("gender")]
public char Gender{get;set;}
[JsonPropertyName("birthdate")]
public DateTime Birthdate{get;set;}
[JsonPropertyName("maritalstatus")]
public string MaritalStatus{get;set;}
[JsonPropertyName("Social")]
public string SocialSecurityNumber{get;set;}
public string MedicareNumber{get;set;}
public string MedicaidNumber{get;set;}
}