Coder Perfect

When serializing using, how can I alter property names?


In a C# DataSet object, I have some data. I can serialize it right now using a converter like this

DataSet data = new DataSet();
// do some work here to populate 'data'
string output = JsonConvert.SerializeObject(data);

When publishing to the.json file, however, this uses the property names from the data. I’d like to alter the property names to something more interesting (for example, from ‘foo’ to ‘bar’).

“JsonPropertyAttribute… allows the name to be modified,” according to the documentation’s ‘Serializing and Deserializing JSON’ ‘Serialization Attributes’ section. However, there isn’t a single example. Does anyone know how to modify the name of a property using a JsonPropertyAttribute?

(This is a direct link to the documentation.)

The documentation for appears to be lacking. I’ll try to have it added to the official docs if you have a fantastic example. Thanks!

Asked by culix

Solution #1

The [JsonProperty] feature, which allows you to define an alternative name for the property you want to control, can be used to adorn it:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

Answered by Darin Dimitrov

Solution #2

Renaming can also be done by constructing a custom resolver if you don’t have access to the classes to update the properties or don’t want to use the same rename property all the time.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
        property.PropertyName = "Short";
    return property;

Then, request serialization and provide the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {“Short”:”prop value”} instead of {“LongPropertyName”:”prop value”}

More information about custom resolvers may be found here.

Answered by StingyJack

Solution #3

There’s also the option of employing a specific NamingStrategy, which may be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

Predefined naming strategies, such as CamelCaseNamingStrategy, are available, but you can also create your own.

Various naming techniques are implemented here:

Answered by JotaBe

Post is based on