My class has a property 'PropertyA', I want this to appear as 'PropertyB' in a JSON object when it's serialized. Is there any sort of attribute I can use?
Asked
Active
Viewed 2.3k times
18
-
3Which JSON serializer are you using? JavaScriptSerializer? JSON.NET? DataContractJsonSerializer? ...? – Marc Gravell Sep 17 '12 at 09:05
-
What JSON serialization library are you using? – AlSki Sep 17 '12 at 09:05
-
Sorry, should've gave more details - DataContractJsonSerializer is what I'm using. Thanks. – Sep 17 '12 at 09:06
1 Answers
31
For Json.NET
and DataContractJsonSerializer
use DataMemberAttribute
:
[DataMember(Name="PropertyB")]
T PropertyA { ... }
Make sure that your class is decorated with the [DataContract]
attribute as well.
If you're using JavaScriptSerializer, you need to create derived implementation, as described here: JavaScriptSerializer.Deserialize - how to change field names

Ohad Schneider
- 36,600
- 15
- 168
- 198

Bartosz
- 3,318
- 21
- 31
-
and if I do not have access to change the DataMenber property? can I add a translator or something like that at serializing time? – rolivares Oct 30 '13 at 12:35
-
http://stackoverflow.com/questions/13091862/change-the-way-json-net-serializes-property-names – Bartosz Oct 30 '13 at 12:39
-
3Also don't forget to add `[DataContract]` on top of the class – Hossein Narimani Rad Aug 25 '17 at 04:01
-
[DataContract] was what I needed as well. Thanks @HosseinNarimaniRad ! – Mason11987 Feb 13 '18 at 19:28
-
ATTENTION! Adding `[DataContract]` does change the serialization logic. Without it all properties will be serialized, after decorating the class with it only properties decorated with `DataMemberAttribute` will be serialized/deserialized. – Rekshino Jul 05 '21 at 17:48