c# - 使用路径和值更新 JSON 对象

标签 c# json json.net

我有一个 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/

相关文章:

c# - Newtonsoft Json 反序列化为 C# Datagridview

c# - Socket.ReceiveAsync 和 SslStream

c# - 响应 BinaryWrite 不适用于 Android 浏览器

c# - 在 .Net Core 中使用弱事件

javascript - 将多维输入数组转换为 JSON

asp.net - ajax请求返回json数组,IE6/7正在缓存它并且数据不新鲜

c# - 自定义属性类是否继承 "Inherited"AttributeUsage 标志?

javascript - 如何使用 JSONLoader 更改 Three.js 加载对象的颜色

javascript - 为什么 AngularJS "$http.get().then(...)"适用于纯文本文件,但不适用于 JSON 文件?

c# - 检测反序列化对象是否缺少 Json.NET 中 JsonConvert 类的字段