Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
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!
You can create different naming strategies, then create different settings, each setting has a Contract resolver, each contract resolver has a naming strategy, then you supply for each settings the naming strategy you want to use,
something like this
public static class JsonSerializingSettings {
public static JsonSerializerSettings JsonUnModified{ get; set; } = new JsonSerializerSettings
ContractResolver = new DefaultContractResolver() {
NamingStrategy = new UnmodifiedNamingStrategy()
public static JsonSerializerSettings JsonDefault { get; set; } = new JsonSerializerSettings
ContractResolver = new DefaultContractResolver() {
NamingStrategy = new DefaultNamingStrategy()
public class UnmodifiedNamingStrategy : NamingStrategy {
protected override string ResolvePropertyName(string name) {
return name;
and when you want to use it
var requestJson = JsonConvert.SerializeObject(contact,JsonSerializingSettings.JsonDefault);
// Serialized Object requestJson:
// "name" = "Harber"
var requestJson = JsonConvert.SerializeObject(contact,JsonSerializingSettings.JsonUnModified);
// Serialized Object requestJson:
// "Lastname" = "Harber"
–
–
–