Shuping
Shuping

Reputation: 5468

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?

Upvotes: 6

Views: 4325

Answers (3)

Oliver
Oliver

Reputation: 9002

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"
}"

Upvotes: 12

Shuping
Shuping

Reputation: 5468

The post http://blog.alexonasp.net/post/2012/04/05/Lowercase-JSON-with-ASPNET-Web-API.aspx exactly answers my question.

Upvotes: 1

sanpaco
sanpaco

Reputation: 815

This may not be the best solution, but in a similar situation I've just returned a json formatted string which is in the format that I want instead of using the automatic serialization. You might be able to find other serialization libraries out there that allow you to do what you want.

Upvotes: 0

Related Questions