Псевдонимы для свойств анонимного типа - PullRequest
1 голос
/ 13 февраля 2012

Возможно ли при создании анонимного типа также создавать псевдонимы для имен свойств?

Проблема, с которой я сталкиваюсь, заключается в том, что имена моих свойств довольно большие, и я пытаюсь сохранить данные 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 Ответ

1 голос
/ 15 марта 2013

Следующий фрагмент кода:

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 легкими, не так ли?

PS Вот второе решение:

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

PPS Вот еще одно решение - кажется, что решение задачи выполняется напрямую.путем создания анонимного объекта с псевдонимами:

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