C#解析轻松的JSON以创建一棵树 [英] c# parsing relaxed json to make a tree
问题描述
所以我需要像这样解析文件:
So I need to parse file looking alike this:
{
pl: {
GENERIC: {
BACK: "COFNIJ",
WAIT: "CZEKAJ",
PAGES: {
ABOUTME: {
ID: "ID",
},
INFO: {
STATUS: "STATUS",
}
}
},
TOP_MENU: {
LOGGED: "Zalogowany",
OPTIONS: "Opcje",
}
},
en: {
GENERIC: {
BACK: "BACK",
WAIT: "WAIT",
PAGES: {
ABOUTME: {
ID: "ID",
},
INFO: {
STATUS: "STATUS",
}
}
},
TOP_MENU: {
LOGGED: "Logged",
OPTIONS: "Options",
}
}
}
但是我不知道文件将包含多少个元素,因此我无法创建用于解析此文件的类.
But I don't know how many elements the file will have, so I can't create class to parse this file.
- 我的第一个问题是如何在C#中用双引号将文件中的无引号"元素包装起来,以使该文件json可解析?
- 如何将上述json文件解析为树数据结构,因此它将如下所示:
示例树 ,因此我可以在控制台上输出每片叶子带有路径的节点,"en"和"pl"子树中的值?
例如: 路径:通用/后退en:后退" pl:"cofnij".
- My first question is how to wraped in c# the "no quotes" elements in file with double quotes to make this file json parsable ?
- How to parse above json file to tree data struture so it will looked like this:
Sample tree, so i can output on console every leaf node with path to it, an values in "en" and "pl" subtree ?
For example: path: generic/back en:"back" pl:"cofnij".
我已经尝试使用Dictionary<string, dynamic> dictionary = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(file);
将上面的宽松json转换为有效json后,可以获取主键,但是我认为树结构将是更有效的方法.
感谢您的帮助!
I've already tried to use Dictionary<string, dynamic> dictionary = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(file);
to get main keys, after converting above relaxed json to valid json, but I think the tree structure will be the more effective way.
Thanks for any help!
推荐答案
您的第一个问题已在此处提出:解析非标准JSON
Your first question was already asked here: Parsing non-standard JSON
The second question sounds a bit like this one: Your first question was already asked here: Deserialize JSON into C# dynamic object?
您可以创建一个动态对象
You could create a dynamic object
dynamic myObj = JsonConvert.DeserializeObject(json);
foreach (Newtonsoft.Json.Linq.JProperty jproperty in myObj)
{
//..
}
,然后对其进行预处理以创建树结构.这可能有帮助:如何反映成员动态对象?
and then preprocess it to create the tree structure. This could help: How do I reflect over the members of dynamic object?
这是通过遍历属性来将反序列化的动态转换为树结构的方法:
This is how you can convert your deserialized dynamic to a tree structure by iterating through the properties:
public void Convert()
{
dynamic myObj = JsonConvert.DeserializeObject(json);
PrintObject(myObj, 0);
}
private void PrintObject(JToken token, int depth)
{
if (token is JProperty)
{
var jProp = (JProperty)token;
var spacer = string.Join("", Enumerable.Range(0, depth).Select(_ => "\t"));
var val = jProp.Value is JValue ? ((JValue)jProp.Value).Value : "-";
Console.WriteLine($"{spacer}{jProp.Name} -> {val}");
foreach (var child in jProp.Children())
{
PrintObject(child, depth + 1);
}
}
else if (token is JObject)
{
foreach (var child in ((JObject)token).Children())
{
PrintObject(child, depth + 1);
}
}
}
这篇关于C#解析轻松的JSON以创建一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!