David Thielen
David Thielen

Reputation: 32926

How do I override a name in JSON returned by ASP.NET

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?

Upvotes: 0

Views: 156

Answers (2)

shakib
shakib

Reputation: 5469

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.

Upvotes: 4

Robert McKee
Robert McKee

Reputation: 21477

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?

Upvotes: 0

Related Questions