使用动态变量解析 JSON 块
我从 URL 中获取 JSON 对象并使用 JSON.NET 解析它。我能够很好地解析具有定义变量的数据块,但是当涉及到 var:value 的随机集合时 - 我陷入困境。
示例(松散类型):
{"FNAME":"乔","LNAME":"doe",
"BodyType":{"身高":180,"体重":"200","种族":"白色","头发":"黑色"},
"BELONGINGS":{"shirt":"black","Money":15,"randomThing":"anyvar"},
"Signs":{"tattoo":0,"scar":"forehead","glasses":"dorky"}
}
我正在将其转换为
类人
如果我无法预测物品和标志的属性,我该如何处理它们?
{
公共字符串 FNAME;
公共字符串 LNAME;
公共 BodyType bodyType;
民众 ?????财物;
民众 ?????标志;
}
I'm grabbing JSON object from an URL and parsing it with JSON.NET. I was able to parse blocks of data with defined variables just fine, but when it comes to random collection of var:value - i'm stuck.
Example(loosely typed):
{"FNAME":"joe","LNAME":"doe",
"BodyType":{"height":180,"weight":"200","race":"white","hair":"black"},
"BELONGINGS":{"shirt":"black","Money":15,"randomThing":"anyvar"},
"Signs":{"tattoo":0,"scar":"forehead","glasses":"dorky"}
}
I'm casting this to
Class Person
{
public string FNAME;
public string LNAME;
public BodyType bodyType;
public ????? belongings;
public ????? signs;
}
How do I handle belongings and signs if i cannot predict their properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种方法可以在运行时不知道内容的情况下处理它们。
第一种方法是使用 JSON.Net 的
JObject
,它将处理您提到的情况以及层次结构。第二种方法是使用 System.Dynamic 的
ExpandoObject
,它是最近版本的 JSON.Net 新支持的。不幸的是,它不能完全处理层次结构,但 JSON.Net 在遇到层次结构时会依靠JObject
来支持它们。出于您的目的,它可能更简单。这是一个包含您给出的代码片段和定义的示例。另请注意,
ExpandoObject
可直接转换为IDictionary
,而JObject
具有访问属性的显式方法。Person对应于
ExpandoObject
,JPerson对应于JObject
。There's two ways of handling them without knowing the contents at runtime.
The first way is to use JSON.Net's
JObject
, which will handle the case you've mentioned, plus hierarchies.The second way is to use System.Dynamic's
ExpandoObject
, which is newly supported by recent releases of JSON.Net. Unfortunately it doesn't quite handle hierarchies, but JSON.Net falls back ontoJObject
to support them when encountered. For your purposes, it might be more straightforward.Here's an example with the snippet and definitions you've given. Also note that
ExpandoObject
is directly castable toIDictionary<string, object>
, whereasJObject
has explicit methods to access properties.Person corresponds to
ExpandoObject
, and JPerson corresponds toJObject
.嗯,它们肯定是 JSON 对象,对吧,JSON 对象是将字符串映射到某些内容的关联数组。所以我将它们表示为
Dictionary
——字符串到某些东西的映射。Well, they're sure to be JSON objects, right, and JSON objects are associative arrays mapping strings to something. So I'd represent them as
Dictionary<string, dynamic>
-- a map of strings to somethings.