I have a class in my project which needs to be serialized for two different use cases. As I can't add two diffrent attributes to on property I would like to serialize the objects of the class one time with the [JsonProperty("attributname")] decleration and one time with the property name it self.
For ex:
public class Contact
{
[JsonProperty("name")]
public string Lastname { get; set; }
}
public class Program
{
public void SerializeByJsonPropertyName()
{
var contact = new Contact()
{
Lastname = "Harber"
}
var requestJson = JsonConvert.SerializeObject(contact);
// Serialized Object requestJson:
// {
// "name" = "Harber"
// }
}
public void SerializeByPropertyName()
{
var contact = new Contact()
{
Lastname = "Harber"
}
var requestJson = JsonConvert.SerializeObject(contact /*, ? Setting ?*/);
// Serialized Object requestJson:
// {
// "Lastname" = "Harber"
// }
}
}
The first szenario works totaly fine, but for the second szenario I could´t find any solution. Except creating two classes or duplicate the properties in my class.. IS there any setting in Newtonsofts JsonConverter for doing this?
Thanks for your help!