'json deserialized property name to default object name
I have a deserialized object property that taken from a web service. I resemble the property name based on the json object. For example:
User.cs
public class UserProfileDTO
{
[JsonProperty("user_ext_fullname")]
public string Fullname { get; set; }
[JsonProperty("user_ext_dateofbirth")]
public string DateOfBirth { get; set; }
}
Controller
userdto = JsonConvert.DeserializeObject<UserProfileDTO>(result);
return userdto;
The issue is that I want to refer the naming object to be "Fullname" not "ext_user_fullname" on the later output. Is there any way to override the jsonproperty name to my default object name?
Current result
"user_ext_fullname": "emir",
"user_ext_dateofbirth": null,
expected result
"fullname": "emir",
"dateOfBirth": null,
Solution 1:[1]
try this
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()
});
output
{"fullname":"name","dateOfBirth":"DOB"}
class
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |
