我希望在我的JSON (Newtonsoft.Json)输出中获取我的C#7元组属性名称。
我的问题是:
当我想将我的元组转换为不支持参数名称的JSON格式时,遇到了困难。
例如,以下是我的“Test2”方法及其JSON输出:
例如,以下是我的“Test2”方法及其JSON输出:
public void Test2()
{
var data = GetMe2("ok");
var jsondata = JsonConvert.SerializeObject(data);//JSON output is {"Item1":5,"Item2":"ok ali"}
}
public (int MyValue, string Name) GetMe2(string name)
{
return (5, name + " ali");
}
JSON输出是 "{"Item1":5,"Item2":"ok ali"}",但我希望得到 "{"MyValue":5,"Name":"ok ali"}";
这并不是不可能的,因为我可以在运行时获取属性名称:
foreach (var item in this.GetType().GetMethods())
{
dynamic attribs = item.ReturnTypeCustomAttributes;
if (attribs.CustomAttributes != null && attribs.CustomAttributes.Count > 0)
{
foreach (var at in attribs.CustomAttributes)
{
if (at is System.Reflection.CustomAttributeData)
{
var ng = ((System.Reflection.CustomAttributeData)at).ConstructorArguments;
foreach (var ca in ng)
{
foreach (var val in (IEnumerable<System.Reflection.CustomAttributeTypedArgument>)ca.Value)
{
var PropertyNameName = val.Value;
Console.WriteLine(PropertyNameName);//here is property names of C#7 tuple
}
}
}
}
dynamic data = attribs.CustomAttributes[0];
var data2 = data.ConstructorArguments;
}
}