访问名称中带有点的属性 [英] Accessing properties with a dot in their name

查看:78
本文介绍了访问名称中带有点的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反序列化JSON.我的根对象具有单个属性"en.pickthall".我正在使用动态类型来读取我的JSON.我以为我可以取消.".在属性中,因为它是本地JSON文件,但是必须有某种方法可以访问此类属性

I am trying to deserialize JSON. My root object has a single property "en.pickthall". I am using dynamic type for reading my JSON. I thought I could just do away with "." in the property since its a local JSON file but then there must be some way to access such a property

var result = App_Code.FileIOHelper.ReadFromDefaultFile("ms-appx:///Assets/en.pickthall.json");

dynamic stuff = JsonConvert.DeserializeObject(result);

foreach(var x in stuff.(en.pickthall)) //Tried this intellisense didn't like it
{

}

推荐答案

C#没有任何引用标识符的方式.如果不是有效的标识符,则唯一的选择就是反射.

C# doesn't have any way of quoting identifiers. If it's not a valid identifier, your only option is reflection.

但是,您的JSON解串器返回的对象可能会更改了标识符,以使其可在C#中使用-您可能希望枚举所有属性,以检查情况是否如此.具有索引器的动态对象也可能是一种解决方案(例如允许stuff["en.pickthall"]).

However, it's possible the object returned by your JSON deserializer changed the identifiers to make them useable in C# - you might want to enumerate all the properties to check if that is the case. A dynamic object with indexers might also be a solution (allowing e.g. stuff["en.pickthall"]).

另一种选择是更改序列化程序映射属性的方式.例如,Newtonsoft.Jsoft允许您使用IContractResolver对其进行自定义.以这种方式将.替换为更C#的东西非常容易.

Another alternative is to change the way the serializer maps properties. For example, Newtonsoft.Jsoft allows you to customize this using a IContractResolver. It's quite easy to replace the . for something more C#-sane in this way.

这篇关于访问名称中带有点的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆