I have searched web for my question without success, so I post question here.
I am using MVC4 Web API for providing JSON data to client. Because C# uses Pascal naming convention, so by default the client received JSON data are also in Pascal naming convention, how do I customize this to return camel naming convention in JSON?
another issue is how to change the serialized name? for example, in C# I have a property named "Description", but in order to reduce the data size, I would like to serialize it as "descr" in JSON, how to achieve this?
The Web API uses JSON as the default serialization. The Web API serializes all the public properties into JSON. In the older versions of Web API, the default serialization property was in PascalCase. When we are working with . NET based applications, the casing doesn't matter.
JSON formatting is provided by the JsonMediaTypeFormatter class.
By default, Web API produces XML but if there is need for JSON, given syntax will do it. Open WebApiConfig. cs file in solution and add mentioned line in it as shown in example.
I know this is an old post, but I thought it was worth adding a reference to Json.Net:
API Reference
Nuget Page
You can set the name that each property will serialize to and from using the JsonProperty
attribute:
public class MyModel
{
[JsonProperty("myJsonProp")]
public string MyJsonProperty { get; set; }
}
Usage:
//Serialize
var json = Newtonsoft.Json.JsonConvert.SerializeObject(instanceOfMyModel);
//De-serialize
var deserialized = Newtonsoft.Json.JsonConvert.DeSerializeOject<MyModel>(json);
The resulting Json:
"{
"myJsonProp" : "value"
}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With