18

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?

1 Answers1

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
  • 3
    Also 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