culix culix - 4 years ago 367
C# Question

How can I change property names when serializing with

I have some data in a C# DataSet object. 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);

However, this uses the property names from
when printing to the .json file. I would like to change the property names to be something different (say, change 'foo' to 'bar').

In the documentation, under 'Serializing and Deserializing JSON' -> 'Serialization Attributes' it says "JsonPropertyAttribute... allows the name to be customized". But there is no example. Does anyone know how to use a JsonPropertyAttribute to change the property name to something else?

(Direct link to documentation)'s documentation seems to be sparse. If you have a great example I'll try to get it added to the official documentation.

Answer Source

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

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

Documentation: Serialization Attributes

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download