0

I have the following code in an ASP.NET Web API 2 app:

[DataMember(Name = "override")]
public bool? _override;

But the JSON I receive has that member named _override, not override. How can I change the naming in the JSON?

Craig W.
  • 17,838
  • 6
  • 49
  • 82
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • Would this help? http://stackoverflow.com/questions/4686817/serialize-net-object-to-json-controlled-using-xml-attributes – Chetan Apr 23 '15 at 20:57
  • I don't understand, you're receiving this JSON from somewhere and inside the JSON it has a name you want to change? The answer then is talk to whoever is sending you the JSON and ask them to change it. – Craig W. Apr 23 '15 at 20:59
  • My ASP.NET Web API server app has the above declaration. ASP.NET creates the JSON from a call where I pass back the object that includes the above member and ASP.NET JSONifies the object based on the object names. – David Thielen Apr 23 '15 at 21:01
  • 2
    `[JsonProperty(PropertyName = "override")]` attribute should do it – shakib Apr 23 '15 at 21:11
  • @shakib - that was it! If you write that as an answer I'm happy to mark it as the solution. thanks - dave – David Thielen Apr 23 '15 at 21:32
  • @DavidThielen added as answer. cheers – shakib Apr 23 '15 at 21:45

2 Answers2

4

As asp.Net web API 2 uses Json.NET internally for json serialization/deserialization,

JsonProperty attribute can be used to override property name on serialization.

so [JsonProperty(PropertyName = "override")] should do the trick.

Thanks.

shakib
  • 5,449
  • 2
  • 30
  • 39
0

How about using the name you want to output? public bool? @override;

You can also use the DataMember(Name="override) attribute on your method, and DataContract attribute on your class, and then use the DataContractJsonSerializer class to serialize it as well.

See this post for a complete example on how to use DataContractJsonSerializer: JavaScriptSerializer - how to deserialize a property with a dash ("-") in it's name?

Community
  • 1
  • 1
Robert McKee
  • 21,305
  • 1
  • 43
  • 57