Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CamelCase JSON WebAPI Sub-Objects (Nested objects, child objects)

I'm creating a complex object with children (nested objects) to be returned from my web api controller. The object contains list of other object types. These sub-object types within the list follow the pascal casing 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 WebAPI does not camel case each of the properties of the sub-items. For example the first person in the persons list should have and attributes of id, name instead of the .NET pascal case of Id, Name. The same should apply for all the other sub items.

like image 579
Andre Young Avatar asked Nov 02 '25 15:11

Andre Young


2 Answers

You can configure JSON.NET to produce camel case names in your application startup. Code snippet from Scott Allen's post:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
like image 106
Ufuk Hacıoğulları Avatar answered Nov 04 '25 08:11

Ufuk Hacıoğulları


I had the same problem. I am returning an object for grid population. It has some properties like Rows, Page, Total etc. Setting the contract resolver to camel case solves the problem for properties at top level. But if any property contains a list of objects with pascal cased property names, it does not changes their case.

So here is what I did to work around the 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 Rows holds the list of objects. Here I was returning list of model objects. Model class looks like :

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 is 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
                };
            }
        }

[DataMember(Name ="")] attribute specifies what name to use for the property when the object is serialized.

Hope this helps!

like image 28
Mayank Sharma Avatar answered Nov 04 '25 07:11

Mayank Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!