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?
- 3Which JSON serializer are you using? JavaScriptSerializer? JSON.NET? DataContractJsonSerializer? ...?Marc Gravell– Marc Gravell2012-09-17 09:05:41 +00:00Commented Sep 17, 2012 at 9:05
- What JSON serialization library are you using?AlSki– AlSki2012-09-17 09:05:59 +00:00Commented Sep 17, 2012 at 9:05
- Sorry, should've gave more details - DataContractJsonSerializer is what I'm using. Thanks.user1017882– user10178822012-09-17 09:06:06 +00:00Commented Sep 17, 2012 at 9:06
Add a comment |
1 Answer
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
5 Comments
rolivares
and if I do not have access to change the DataMenber property? can I add a translator or something like that at serializing time?
Hossein Narimani Rad
Also don't forget to add
[DataContract] on top of the classMason11987
[DataContract] was what I needed as well. Thanks @HosseinNarimaniRad !
Rekshino
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.