CamelCase JSON WebAPI entities (nested objects, child objects)

I am creating a complex object with children (nested objects) that will be returned from my api web controller. The object contains a list of other types of objects. These types of sub-objects in the list follow the pascal shell used in .NET.

var persons = peopleLookup.Values; var users = userLookup.Values; var roles = rolesLookup.Values; var groups = groupLookup.Values; var roleAssignments = roleAssignmentLookup.Values; var groupMembers = groupMemberLookup.Values; return new { persons, users, roles, roleAssignments, groups, groupMembers }; 

My problem is that the WebAPI does not execute camel in each of the properties of the subitems. For example, the first person in the list of persons should also have id, name attributes instead of the case of .NET pascal Id, Name. The same should apply to all other elements.

+1
json c # asp.net-web-api camelcasing pascalcasing
Apr 29 '14 at 16:47
source share
4 answers

You can configure JSON.NET to create camel body names when you run your application. A snippet of code from a post by Scott Allen :

 var formatters = GlobalConfiguration.Configuration.Formatters; var jsonFormatter = formatters.JsonFormatter; var settings = jsonFormatter.SerializerSettings; settings.Formatting = Formatting.Indented; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
+7
Apr 29 '14 at 19:10
source share

I had the same problem. I am returning an object for the grid. It has some properties, such as lines, page, total, etc. Installing a resolution device on a camel case solves the problem for properties at the top level. But if any property contains a list of objects with property names with pascal, this does not change their case.

So, here is what I did to solve this problem.

Grid object with data to return

 [DataContract] public class GridProperties<T> { [DataMember] public List<T> Rows { get; set; } [DataMember] public int Records { get; set; } [DataMember] public int Total { get; set; } [DataMember] public int Page { get; set; } } 

Here Lines contain a list of objects. Here I returned a list of model objects. The model class is as follows:

 public class ClientListModel { [DataMember(Name = "clientId")] public int ClientId { get; set; } [DataMember(Name = "firstName")] public string FirstName { get; set; } [DataMember(Name = "lastName")] public string LastName { get; set; } [DataMember(Name = "startDate")] public DateTime? StartDate { get; set; } [DataMember(Name = "status")] public string Status { get; set; } public ClientListModel() {} } 

And below shows how I returned JSON data from my API controller

  [HttpGet] public GridProperties<ClientListModel> GetClients(int page) { const int rowsToDisplay = 10; try { IEnumerable<ClientListModel> clientList = null; using (var context = new AngularModelConnection()) { clientList = context.Clients.Select(i => new ClientListModel() { ClientId = i.Id, FirstName = i.FirstName, LastName = i.LastName, StartDate = i.StartDate, Status = (i.DischargeDate == null || i.DischargeDate > DateTime.Now) ? "Active" : "Discharged" }); int total = clientList.Count(); //Get count of total records int totalPages = Convert.ToInt16(Math.Ceiling((decimal) total/rowsToDisplay)); //Get total page of records return new GridProperties<ClientListModel> { Rows = clientList.Skip((page - 1)*rows).Take(rows).ToList(), Records = total, Total = totalPages, Page = page }; } } catch (Exception exc) { ExceptionLogger.LogException(exc); return new GridProperties<ClientListModel> { Rows = null, Records = 0, Total = 0, Page = page }; } } 
Attribute

[DataMember(Name ="")] indicates which name should be used for the property when the object is serialized.

Hope this helps!

+1
Dec 18 '14 at 8:08
source share

I had a similar problem with nested objects when trying to return a DataSet with relationships from WebAPI. Using ExpandoObject did the trick for me, maybe this will help you.

 private static object ConvertDataSetWithRelationsToCamelCaseObject(DataSet ds) { foreach (DataRelation relation in ds.Relations) { relation.Nested = true; } var doc = new XmlDocument(); doc.LoadXml(ds.GetXml()); var pascalCaseJson = JsonConvert.SerializeXmlNode(doc, Formatting.None, true); var pascalCaseObject = JsonConvert.DeserializeObject<ExpandoObject>(pascalCaseJson); var camelCaseJson = JsonConvert.SerializeObject(pascalCaseObject, Formatting.Indented, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver(),}); return JsonConvert.DeserializeObject(camelCaseJson); } 

Sample code for creating a dataset with relationships:

 var dsTasks = new Tasks().Find(sqlParameters); var dsValidators = new Validators().Find(sqlParameters); var dsProperties = new ValidatorProperties().Find(sqlParameters); dsTasks.Tables[0].TableName = "Tasks"; dsValidators.Tables[0].TableName = "Validators"; dsProperties.Tables[0].TableName = "ValidatorProperties"; var ds = new DataSet {DataSetName = "ValidatorsByTask"}; ds.Tables.Add(dsTasks.Tables[0].Copy()); ds.Tables.Add(dsValidators.Tables[0].Copy()); ds.Tables.Add(dsProperties.Tables[0].Copy()); ds.Relations.Add("Task_Validators", ds.Tables["Tasks"].Columns["Id"], ds.Tables["Validators"].Columns["TaskId"]); ds.Relations.Add("Validator_Properties", ds.Tables["Validators"].Columns["Id"], ds.Tables["ValidatorProperties"].Columns["ValidatorId"]); var data = ConvertDataSetWithRelationsToCamelCaseObject(ds); 
0
Aug 15 '14 at 16:21
source share

A short and very simple solution for formatting JSON output in CamelCase compared to .NET PascalCase by default.

Add the following two lines to your WebApiConfig.cs file (in the App_Start folder on WebApi 2):

 // Get the default json formatter var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); // Switch from PascalCase to CamelCase jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
-one
Mar 18 '15 at 4:37
source share



All Articles