How do you handle differing naming conventions when serializing C# objects to JSON?
You could use JSON.net to serialize the data for you, and you can even tell it to use camelCase. This question asks something similar. Here's a code example for reference:
Product product = new Product { ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc), Name = "Widget", Price = 9.99m, Sizes = new[] { "Small", "Medium", "Large" }};string json =JsonConvert.SerializeObject( product, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver()});
Don't worry about the performance of JSON.net either, as the performance of it versus native serialization is comparable (better in most cases).
If you are using the DataContractJsonSerializer
, you can specify the name using the DataMemberAttribute.Name
property:
[DataContract]public class User{ [DataMember(Name = "user_id")] public int UserId { get; set; } [DataMember(Name = "user_name")] public string UserName { get; set; }}
will serialize to
{"user_id":123,"user_name":"John Doe"}
I just use what the server gives me.
C#
public class Person{ public string Name { get; set; } public string Email { get; set; }}
JS:
$.ajax({ ... success: function(data) { var person = data; alert(person.Name); }});