【问题标题】:Update JSON object using path and value使用路径和值更新 JSON 对象
【发布时间】:2016-03-17 09:48:36
【问题描述】:

我有一个 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。 当然原始文件中的属性可以不同。

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    您可以使用此函数将 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;

    【讨论】:

    • 它很好用,但是当你有一个属性时它会失败:prop1.prop2.prop2
    【解决方案2】:

    您可以利用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);
    }
    

    【讨论】:

      【解决方案3】:

      不使用动态:

      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;
      }
      

      产生预期的输出

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-26
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 2012-01-31
        相关资源
        最近更新 更多