[英]How to parse unknown Json file with Json.net in C#
I'm able to get a dynamic Json object using 我可以使用获取动态Json对象
dynamic obj = JsonConvert.DeserializeObject(json);
It seems to be a nested object structure 它似乎是一个嵌套的对象结构
I need to graph every variable in the json file, but the json file structure changes often 我需要绘制json文件中的每个变量图,但是json文件结构经常更改
Is there a way to parse through this structure using nested foreach() statements? 有没有办法使用嵌套的foreach()语句来解析此结构? If not, can can I parse it by accessing each element via a string like a Dictionary? 如果没有,我可以通过像字典那样的字符串访问每个元素来解析它吗?
for example something like: 例如:
if(obj["Item1"]["Parameter3"]["Value2"]` != NULL)
int number = obj["Item1"]["Parameter3"]["Value2"]`
Thanks, 谢谢,
Yes there is an API for querying dynamically. 是的,有一个用于动态查询的API。 See the documentation here: https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm 请参阅此处的文档: https : //www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm
Code looks something like this: 代码看起来像这样:
JObject rss = JObject.Parse(json);
var postTitles =
from p in rss["channel"]["item"]
select (string)p["title"];
Finally figured this api out 终于弄清楚了这个api
Some JToken entries have a list of values, others have a name and value. 一些JToken条目具有值列表,其他JToken条目具有名称和值。 You have to sort which one is which prior to parsing it. 您必须先解析哪个,然后再解析。
This will create a Dictionary with every entry in the Json file 这将为Json文件中的每个条目创建一个Dictionary
void SomeFunction()
{
Dictionary<string, decimal> json_data = new Dictionary<string, decimal>();
dynamic json_obj = JsonConvert.DeserializeObject(json);
Linearize(ref json_data, json_obj);
}
void Linearize(ref Dictionary<string, decimal> input_dict, JToken json_data, string key = "")
{
int i;
if (json_data != null)
{
if (json_data.HasValues)
{
i = 0;
foreach (dynamic entry in json_data)
{
//Add a Name field if it exists
Type typeOfDynamic = entry.GetType();
if (typeOfDynamic.GetProperties().Where(p => p.Name.Equals("Name")).Any())
key += entry.Name + ".";
//If JToken is an Array
if (((JToken)entry).HasValues)
{
Linearize(ref input_dict, entry, key + "[" + i++ + "]" + ".");
}
//If JToken is a data type
else if (entry.Type == JTokenType.String || entry.Type == JTokenType.Float || entry.Type == JTokenType.Integer)
{
decimal output;
if (decimal.TryParse(entry.ToString(), out output))
input_dict.Add(key + "[" + i++ + "]", output);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.