使用路径和值更新JSON对象 [英] Update JSON object using path and value

查看:51
本文介绍了使用路径和值更新JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,其中包含以下格式的路径和值:

I have a csv file that contains paths and values in the following format:

path;value
prop1.prop2.1;hello
prop1.prop2.2;world
prop1.prop2.3;!
prop1.prop3.test;hi
prop1.prop4;value

然后我要用json来获取它:

And I wand to get it as json:

{
  "prop1": {
    "prop2": {
      "1": "hello",
      "2": "world",
      "3": "!"
    }
    "prop3": {
      "test": "hi"
    }
    "prop4": "value"
  }    
}

我已经这样解析csv文件:

I've parsed csv file like this:

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 库. 当然原始文件中的属性可以不同.

Could you help me with method, that will create JSON from this dictionary using JSON.Net Library. Of course properties in original file can be different.

推荐答案

您可以使用此函数从字典中以字符串形式返回Json

You can use this function to get the Json back as a string from your Dictionary

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添加一个

you need to add a using System.Dynamic;

这篇关于使用路径和值更新JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆