. net Core JsonElement解析多嵌套动态JSON



我有动态嵌套JSON来自前端。如下所示,只有那些值不为空的键才会被发送。在这种情况下,中间的首字母没有被填充,所以你找不到它:

{
"name": {
"firstname": "fst",
"lastname": "lst"
},
"gender": "male",
"birthdate": "2021-02-09",
"maritalstatus": "Never married",
"id": {
"social": "123456789"
}
}

我已经为每个潜在的属性尝试了这些:

JsonElement lastname;
question1.TryGetProperty("lastname", out lastname);

但寻找一个更体面的方式,例如下面的:

var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true
};
var jsonModel = JsonSerializer.Deserialize<Survey>(obj, options);
var modelJson = JsonSerializer.Serialize(jsonModel, options);

但问题是这种方法只能处理第一级属性,如性别、出生日期、婚姻状况,而不能处理姓、名和社会关系。

如何解决它或任何其他方法我可以尝试,非常感谢!

UPDATE1:

Survey是一个poco,看起来是这样的但远不止这些属性,看到那些注解了吗,我想让它自己完成映射而不是自己完成映射

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

}

试试这个:

dynamic model = JsonConvert.DeserializeObject(jsonStr);

和访问任何你想要的:

var firstName = model.name.firstname;

UPDATE 1:您应该为复杂的字段定义不同的模型。

public class Survey
{
public NameModel Name { get; set; }
public IdModel Id { get; set; }
public char MiddleInitial { get; set; }
public string JrSr { get; set; }
public string Gender { get; set; }
public DateTime Birthdate { get; set; }
public string MaritalStatus { get; set; }
public string MedicareNumber { get; set; }
public string MedicaidNumber { get; set; }
}
public class NameModel
{
public string LastName { get; set; }
public string FirstName { get; set; }
}
public class IdModel
{
public string Social { get; set; }
}

此外,没有必要使用JsonPropertyName,而模型和JSON中的字段名是相等的。

最新更新