How to configure serialized JSON name in MVC4 web API?

I searched the website for my question without success, so I ask the question here.

I use the MVC4 Web API to provide JSON data to the client. Since C # uses the Pascal naming convention, therefore, by default, the client receiving the JSON data is also in the Pascal naming convention, how can I configure it to return the camel naming convention to JSON?

Another problem is how to change the serialized name? for example, in C # I have a property called "Description", but to reduce the size of the data I would like to serialize it as "descr" in JSON, how to do it?

+6
source share
3 answers

I know this is an old post, but I thought it was worth adding a link to Json.Net:

API Reference

Nuget Page

You can set a name in which each property will be serialized to and using the JsonProperty attribute:

 public class MyModel { [JsonProperty("myJsonProp")] public string MyJsonProperty { get; set; } } 

Using:

 //Serialize var json = Newtonsoft.Json.JsonConvert.SerializeObject(instanceOfMyModel); //De-serialize var deserialized = Newtonsoft.Json.JsonConvert.DeSerializeOject<MyModel>(json); 

As a result of Json:

 "{ "myJsonProp" : "value" }" 
+12
source

This may not be the best solution, but in a similar situation, I just returned a formatted json string, which is in the format I want, instead of automatically serializing. You may find other serialization libraries that let you do what you want.

0
source

All Articles