问题描述
所以我需要解析看起来像这样的文件:
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"子树中的值?
例如:路径:generic/back en:"back" pl:"cofnij".
我已经尝试过使用 Dictionary字典 = JsonConvert.DeserializeObject
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
第二个问题听起来有点像这样:您的第一个问题已经在这里问过了:将 JSON 反序列化为 C# 动态对象?
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(_ => " "));
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 以制作一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!