我有一个 csv 文件,其中包含以下格式的路径和值:
path;value
prop1.prop2.1;hello
prop1.prop2.2;world
prop1.prop2.3;!
prop1.prop3.test;hi
prop1.prop4;value
我想将其获取为 json:
{
"prop1": {
"prop2": {
"1": "hello",
"2": "world",
"3": "!"
}
"prop3": {
"test": "hi"
}
"prop4": "value"
}
}
我已经像这样解析了 csv 文件:
Dictionary<string, string> dict = new Dictionary<string, string>();
while (csv.Read())
{
string path = csv.GetField<string>(0);
string value = csv.GetField<string>(1);
dict.Add(path, value);
}
你能帮我提供一个方法吗,该方法将使用 JSON.Net 从该字典创建 JSON图书馆。 当然,原始文件中的属性可以不同。
最佳答案
您可以使用此函数从字典中以字符串形式获取 Json
public static string BuildJson(Dictionary<string, string> dict)
{
dynamic expando = new ExpandoObject();
foreach (KeyValuePair<string, string> pair in dict.Where(x => !string.Equals(x.Key, "path")))
{
string[] pathArray = pair.Key.Split('.');
var currentExpando = expando as IDictionary<string, Object>;
for (int i = 0; i < pathArray.Count(); i++)
{
if (i == pathArray.Count() - 1)
{
currentExpando.Add(pathArray[i], pair.Value);
}
else
{
if (!currentExpando.Keys.Contains(pathArray[i]))
{
currentExpando.Add(pathArray[i], new ExpandoObject());
}
currentExpando = currentExpando[pathArray[i]] as IDictionary<string, Object>;
}
}
}
JObject o = JObject.FromObject(expando);
return o.ToString();
}
您需要添加一个using System.Dynamic;
关于c# - 使用路径和值更新 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36056893/