I have some data in a C# DataSet object. 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);
However, this uses the property names from data
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 Json.net 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)
Json.net's documentation seems to be sparse. If you have a great example I'll try to get it added to the official documentation. Thanks!
Objects are the mapping type in JSON. They map “keys” to “values”. In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”.
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
All fields, both public and private, are serialized and properties are ignored. This can be specified by setting MemberSerialization. Fields on a type with the JsonObjectAttribute or by using the . NET SerializableAttribute and setting IgnoreSerializableAttribute on DefaultContractResolver to false.
You could decorate the property you wish controlling its name with the [JsonProperty]
attribute which allows you to specify a different name:
using Newtonsoft.Json; // ... [JsonProperty(PropertyName = "FooBar")] public string Foo { get; set; }
Documentation: Serialization Attributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With