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?

3
  • 3
    Which JSON serializer are you using? JavaScriptSerializer? JSON.NET? DataContractJsonSerializer? ...? Commented Sep 17, 2012 at 9:05
  • What JSON serialization library are you using? Commented Sep 17, 2012 at 9:05
  • Sorry, should've gave more details - DataContractJsonSerializer is what I'm using. Thanks. Commented Sep 17, 2012 at 9:06

1 Answer 1

32

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

Sign up to request clarification or add additional context in comments.

5 Comments

and if I do not have access to change the DataMenber property? can I add a translator or something like that at serializing time?
Also don't forget to add [DataContract] on top of the class
[DataContract] was what I needed as well. Thanks @HosseinNarimaniRad !
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.