我有一个反序列化的对象属性,它取自web服务。我类似于基于json对象的属性名称。例如:
用户.cs
public class UserProfileDTO
{
[JsonProperty("user_ext_fullname")]
public string Fullname { get; set; }
[JsonProperty("user_ext_dateofbirth")]
public string DateOfBirth { get; set; }
}
控制器
userdto = JsonConvert.DeserializeObject<UserProfileDTO>(result);
return userdto;
问题是,我想将命名对象称为";全名";而不是";ext_user_fullname";在以后的输出中。有什么方法可以将jsonproperty名称重写为我的默认对象名称吗?
当前结果
"user_ext_fullname": "emir",
"user_ext_dateofbirth": null,
预期结果
"fullname": "emir",
"dateOfBirth": null,
尝试这个
var json= "{ "user_ext_fullname":"name","user_ext_dateofbirth":"DOB"}";
var userProfileDto=JsonConvert.DeserializeObject<UserProfileDTO>(json);
json = JsonConvert.SerializeObject(userProfileDto, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
输出
{"fullname":"name","dateOfBirth":"DOB"}
类
public class UserProfileDTO
{
public string Fullname { get; set; }
public string DateOfBirth { get; set; }
public UserProfileDTO (string user_ext_fullname, string user_ext_dateofbirth)
{
Fullname=user_ext_fullname;
DateOfBirth=user_ext_dateofbirth;
}
}