6

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?

3 Answers 3

12

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"
}"
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Oliver, you answer is never late, and I find this is a very grace solution. I never though there is such a attribute before you answer me! thanks.
1

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

Comments

0

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.

1 Comment

I hoped there is an attribute to be put on each property of my model object to declare the formatted name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.