Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change property names when serializing with Json.net?

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!

like image 655
culix Avatar asked Jan 09 '12 23:01

culix


People also ask

What is property name in JSON?

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”.

What is JSON property C#?

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.

What does serializing a JSON mean?

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).

Does JSON net serialize private fields?

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.


1 Answers

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

like image 159
Darin Dimitrov Avatar answered Sep 30 '22 00:09

Darin Dimitrov