CamelCase JSON WebAPI子对象(嵌套对象,子对象)

时间:2014-04-29 16:47:20

标签: c# json asp.net-web-api camelcasing pascalcasing

我正在创建一个带有子对象(嵌套对象)的复杂对象,以便从我的web api控制器返回。该对象包含其他对象类型的列表。列表中的这些子对象类型遵循.NET中使用的pascal大小写。

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

我的问题是WebAPI没有驼峰这个子项的每个属性。例如,人员列表中的第一个人应该具有id,name的属性,而不是Id,Name的.NET pascal案例。同样适用于所有其他子项目。

4 个答案:

答案 0 :(得分:7)

您可以配置JSON.NET以在应用程序启动时生成驼峰案例名称。来自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();

答案 1 :(得分:1)

我遇到了同样的问题。我正在为网格填充返回一个对象。它有一些属性,如Rows,Page,Total等。将合约解析器设置为camel case解决了顶层属性的问题。但是,如果任何属性包含带有pascal cased属性名称的对象列表,则不会更改它们的大小写。

所以这就是我为解决这个问题所做的工作。

包含要返回的数据的网格对象

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

此处Rows包含对象列表。在这里,我返回了模型对象列表。模型类看起来像:

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()
    {}
}

以下是我从API控制器返回JSON数据的方法

    [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 ="")]属性指定序列化对象时要用于属性的名称。

希望这有帮助!

答案 2 :(得分:0)

尝试从WebAPI返回带有关系的DataSet时,我遇到了与嵌套对象类似的问题。使用ExpandoObject为我做了伎俩,也许这会对你有帮助。

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

使用关系创建数据集的示例代码:

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);

答案 3 :(得分:-1)

  

一种简短而简单的解决方案,用于格式化CamelCase中的JSON输出与默认的.NET的PascalCase。

添加到WebApiConfig.cs文件(位于WebApi 2的App_Start文件夹下)以下两行:

// Get the default json formatter 
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();

// Switch from PascalCase to CamelCase
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();