Coder Perfect

When serializing using Json.net, how can I alter property names?

Problem

In a C# DataSet object, I have some data. I can serialize it right now using a Json.net 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 Json.net 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 Json.net 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: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

Answered by JotaBe

Post is based on https://stackoverflow.com/questions/8796618/how-can-i-change-property-names-when-serializing-with-json-net