简体   繁体   English

Json.NET(Newtonsoft)解析一些动态数据(C#)

[英]Json.NET (Newtonsoft) to parse somewhat dynamic data (c#)

using c# - I have a string of valid json, and am attempting to parse it into a Dictionary but am struggling with the syntax to do so. 使用c#-我有一个有效的json字符串,并尝试将其解析为Dictionary,但在语法上却很挣扎。

Here's an example of the data I'd like to parse: 这是我要解析的数据的示例:

{
  "data": {
    "KeyOne": {
      "val": "first!"
      "fooBar": "invalid data not needed",
    },
    "anotherKey": {
      "val": null
    },
    "TheThirdKey": {
      "val": 999
      "fooFooBarBar": "more unneeded data",
    },
    "KeyKeyKey": {
      "val": "super neato something"
    },
    ...

this needs to be moved into a Dictionary<string, object> with some fairly specific rules: 这需要使用一些相当特定的规则移动到Dictionary<string, object>

  1. the ever changing element name is the key ('KeyOne', 'anotherKey'...) - this is unique within the dataset 不断变化的元素名称是键(“ KeyOne”,“ anotherKey” ...)-这在数据集中是唯一的
  2. for the dictionary value, I ONLY need the string or number or null that is the value of ' val ' ('first', null, 999, ...) 对于字典值,我需要字符串或数字或null,即' val '的值('first',null,999等)

so my final dictionary should be something like: 所以我的最终字典应该是这样的:

"KeyOne"     : "first!"
"anotherKey" : null
"TheThirdKey": 999
"KeyKeyKey"  : "super neato something"

I've tried to parse this using different variations of 我试图使用不同的变体来解析

JsonConvert.DeserializeObject<Dictionary<string, object>

I've also tried iterating over the jTokens as such: 我也尝试过遍历jTokens,例如:

JObject jObject = JObject.Parse(jsonString);
List<JToken> jTokens = jObject["data"].Children().ToList();
foreach (JToken jToken in jTokens) { ...

but after so many hours of trying, I am getting embarrassingly nowhere... Hopefully this is something that can be performed with Json.NET, but I have yet to figure it out. 但是经过这么长时间的尝试,我却尴尬地无处可去...希望这可以用Json.NET来完成,但是我还没有弄清楚。

Thoughts? 思考?

You could do it this way: 您可以这样进行:

JObject jObject = JObject.Parse(jsonString);
var dataChildren = jObject["data"].Children().Cast<JProperty>();
Dictionary<string, object> result = dataChildren
       .ToDictionary(x => x.Name, x => x.Value["val"].Value<JValue>().Value);

You will get a Dictionary<string,object> as a result 结果将得到一个Dictionary<string,object>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM