我有一个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();
}
您需要使用系统动态添加;
您可以利用 System.Dynamic.ExpandoObject:
public string ToJson(Dictionary<string, string> props)
{
IDictionary<string, object> json = new System.Dynamic.ExpandoObject() as IDictionary<string, object>;
foreach (var prop in props)
{
string path = prop.Key;
if (String.IsNullOrWhiteSpace(path)) continue;
string[] keys = path.Split('.');
string value = prop.Value;
var cursor = json;
for (int i = 0; i < keys.Length; i++)
{
object innerJson;
if (!cursor.TryGetValue(keys[i], out innerJson))
cursor.Add(keys[i], new System.Dynamic.ExpandoObject() as IDictionary<string, object>);
if (i == keys.Length - 1)
cursor[keys[i]] = value;
cursor = cursor[keys[i]] as IDictionary<string, object>;
}
}
return JsonConvert.SerializeObject(json);
}
不使用动态:
Dictionary<string, object> dictionary = new Dictionary<string, object>();
while (csv.Read())
{
string path = csv.GetField<string>(0);
string value = csv.GetField<string>(1);
dictionary = GetHierarchy(path, value);
}
string serialized = JsonConvert.SerializeObject(dictionary);
Console.WriteLine(serialized);
添加以下方法:
public Dictionary<string, object> GetHierarchy(Dictionary<string, object> root, string path, string value)
{
string[] parts = path.Split('.');
if (parts.Length > 1)
{
if(!root.ContainsKey(parts[0]))
root.Add(parts[0], new Dictionary<string, object>());
Dictionary<string, object> dict = root[parts[0]] as Dictionary<string, object>;
GetMe(dict, path.Replace(parts[0] + ".", string.Empty), value);
}
else
root[parts[0]] = value;
return root;
}
生成预期的输出