【发布时间】:2017-05-24 09:55:25
【问题描述】:
我想在我的 JSON (Newtonsoft.Json) 输出中获取我的 C#7 元组属性名称。 我的问题是: 当我想将我的元组转换为不支持我的参数名称的 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;
}
}
【问题讨论】:
-
啊,我知道这也是你的问题。一般来说,这类特定于库的问题在 GitHub 问题跟踪器上比在 StackOverflow 上更有可能得到回答。我们只能帮助您实施某种自定义方法或拐杖解决方案。
-
为什么要问堆栈溢出问题在你已经发现它还没有在 Json.NET 中实现,并且有一个功能请求?
-
是的,我在添加问题之前看到了。
-
“我希望任何人都可以在我的情况下更改 json 开源项目”。你有理由不能成为那个“任何人”吗?抓住源头,进行更改并提交 PR,而不是等待其他人为您完成。