Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to customize the JSON serialized name in MVC4 Web API?

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?

like image 305
Shuping Avatar asked Nov 02 '12 06:11

Shuping


People also ask

What is JSON serialization in Web API?

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.

Which is a Formatter class for JSON?

JSON formatting is provided by the JsonMediaTypeFormatter class.

Which is more appropriate for requesting JSON instead XML?

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.


1 Answers

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"
}"
like image 181
Oliver Avatar answered Nov 04 '22 12:11

Oliver