匿名类型属性的别名

时间:2012-02-13 09:15:00

标签: json alias anonymous-types anonymous

创建匿名类型是否也可以为属性名称创建别名?

我遇到的问题是我的属性名称相当大,我正在尝试将Json数据保持在最低限度,以使其更轻量级,而不是更改非常具有描述性的实际属性名称,我想知道如果我可以动态创建每个属性的别名?

var result = myModel.Options.Select(l => new  { l.Id, l.LargePropertyName, l.LargePropertyName2 }).ToDictionary(l => l.Id.ToString(), l => new { l.LargePropertyName1, l.LargePropertyName2 });
JavaScriptSerializer serializer = new JavaScriptSerializer();
Json = serializer.Serialize(result);

非常感谢

1 个答案:

答案 0 :(得分:1)

以下代码段:

var resultWithLengthyPropertyNames = new { Identificator = 1, VeryLengthyPropertyName1 = "Fred", VeryLengthyPropertyName2 = "Brooks" };

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var sourceJSON = serializer.Serialize(resultWithLengthyPropertyNames);

System.Console.WriteLine("Source JSON => {0}", sourceJSON);  

string[] propertyNamesAliases = { "ID",  "FN", "LN"};        
var intermediateResult = (IDictionary<string, object>)serializer.DeserializeObject(sourceJSON);
var renamedIntermediateResult = new Dictionary<string, object>();
for (int i = 0; i < propertyNamesAliases.Length; i++)
    renamedIntermediateResult.Add(propertyNamesAliases[i],
        intermediateResult[intermediateResult.Keys.ToArray()[i]]);

var convertedJSON = serializer.Serialize(renamedIntermediateResult);

System.Console.WriteLine("Converted JSON => {0}", convertedJSON);  

导致测试输出:

Source JSON => {"Identificator":1,"VeryLengthyPropertyName1":"Fred","VeryLengthyPropertyName2":"Brooks"}
Converted JSON => {"ID":1,"FN":"Fred","LN":"Brooks"}

建议的解决方案不会创建具有重命名属性名称的新匿名对象,但它确实解决了保持JSON字符串轻量级的任务,不是吗?

P.S。这是第二个解决方案:

var resultWithLengthyPropertyNames = new { Identificator = 1, VeryLengthyPropertyName1 = "Fred", VeryLengthyPropertyName2 = "Brooks" };

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var sourceJSON = serializer.Serialize(resultWithLengthyPropertyNames);

System.Console.WriteLine("Source JSON => {0}", sourceJSON);

Dictionary<string, string> propertyNamesAliases = new Dictionary<string, string>() 
            {
                { "Identificator", "ID"}, 
                { "VeryLengthyPropertyName1", "FN" },
                { "VeryLengthyPropertyName2", "LN" }
            };

var renamedTempResult = new Dictionary<string, object>();

foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(resultWithLengthyPropertyNames))
{
    renamedTempResult.Add(
            propertyNamesAliases[propertyDescriptor.Name],
            propertyDescriptor.GetValue(resultWithLengthyPropertyNames));
}

var convertedJSON = serializer.Serialize(renamedTempResult);

System.Console.WriteLine("Converted JSON => {0}", convertedJSON);

P.P.S。这是另一个解决方案 - 似乎是通过创建具有别名属性的匿名对象直接解决任务:

var resultWithLengthyPropertyNames = new { Identificator = 1, VeryLengthyPropertyName1 = "Fred", VeryLengthyPropertyName2 = "Brooks" };

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

var sourceJSON = serializer.Serialize(resultWithLengthyPropertyNames);

System.Console.WriteLine("Source JSON => {0}", sourceJSON);

var targetObjectTemplate = new { ID = -1, FN = "", LN = "" };

var convertedObject =
            Activator.CreateInstance(targetObjectTemplate.GetType(),
                    resultWithLengthyPropertyNames.GetType()
                .GetProperties()
                .Select(p => p.GetValue(resultWithLengthyPropertyNames))
                .ToArray());

var convertedJSON = serializer.Serialize(convertedObject);

System.Console.WriteLine("Converted JSON => {0}", convertedJSON);