简体   繁体   English

如何将带有点表示法和 arrays 的字符串转换为 json?

[英]How can I convert a string with dot notation and arrays to json?

I'm trying to convert a string that is in dot notation to JSON.我正在尝试将点表示法的字符串转换为 JSON。

For example, in a Dictionary<string, object> I have the key-value pairs of:例如,在Dictionary<string, object>我有以下键值对:

key: "resource.person[0].name"  
value: "bob"

key: "resource.person[1].name"  
value: "dylan"

I have the below code that can convert the dot notation of the key to JSON but it ignores the arrays:我有以下代码可以将键的点表示法转换为 JSON 但它忽略了 arrays:

var formattedDictionary = new Dictionary<string, object>();
   foreach(var pair in returnFields)
   {
      var key = pair.Key;
      var parts = key.Split('.');
      var currentObj = formattedDictionary;
      for (int i = 0; i < parts.Length-1; i++)
      {
         var property = parts[i];
         if (!currentObj.ContainsKey(property))
            currentObj[property] = new Dictionary<string, object>();
         currentObj = (Dictionary<string, object>)currentObj[property];
      }

      currentObj[parts[^1]] = pair.Value;
    }
 return formattedDictionary;

Currently Returns:目前退货:

{
   "resource": {
      "person[0]": {
         "name" : "bob"
      },
      "person[1]": {
         "name" : "dylan"
      }
   }
}

I would like some help modifying the above code to also handle the arrays to give me an output that looks like this我想要一些帮助修改上面的代码来处理 arrays 给我一个看起来像这样的 output

Ideal Return:理想回报:

{
   "resource": {
      "person": [
        {
         "name" : "bob"
        },
        {
         "name" : "dylan"
        }
      ]
   }
}

Thanks!谢谢!

This works for me (using Recursion)这对我有用(使用递归)

private static Dictionary<string, object> CheckAndCreateKey(string key, object value, Dictionary<string, object> dict) 
    {
        if (!key.Contains(".")) 
        {
            dict[key] = value;
            return dict;
        }

        var firstLevel = key.Split('.')[0];
        var remainingParts = key.Replace(firstLevel + ".", ""); 
        var index = -1;
        if (firstLevel.Contains("[")) 
        {
            var bits = firstLevel.Split('[', ']');
            firstLevel = bits[0]; 
            index = int.Parse(bits[1]);
        }

        if (!dict.ContainsKey(firstLevel)) 
        {
            // new property
            var nestedDict = CheckAndCreateKey(remainingParts, value, new Dictionary<string, object>());
            if (index > -1) 
            {
                // this is an Array
                var list = new List<Dictionary<string, object>>();

                while (list.Count <= index) // add require length, in case when index are in the wrong order (e.g. cars[1].make appears first before cars[0].make)
                    list.Add(new Dictionary<string, object>());

                list[index] = nestedDict;
                dict[firstLevel] = list;
                return dict;
            }

            dict[firstLevel] = nestedDict;
            return dict;
        }

        if (index > -1) 
        {
            var list = (List<Dictionary<string, object>>) dict[firstLevel];
            while (list.Count <= index) // add missing items
                list.Add(new Dictionary<string, object>());

            var nestedDict = CheckAndCreateKey(remainingParts, value, (Dictionary<string, object>) list[index]);
            dict[firstLevel] = list;
            return dict;
        }
        
        var current = (Dictionary<string, object>) dict[firstLevel];
        dict[firstLevel] = CheckAndCreateKey(remainingParts, value, current);
        return dict;
    }

    public static Dictionary<string, object> ParseDotNotation(this Dictionary<string, object> input) 
    {
        var formattedDictionary = new Dictionary<string, object>();
        foreach (var pair in input)
        {
            CheckAndCreateKey(pair.Key, pair.Value, formattedDictionary);
        }
        return formattedDictionary;
    }

Perhaps something like也许像

var formattedDictionary = new Dictionary<string, object>();
foreach (var pair in returnFields)
{
    var key = pair.Key;
    var parts = key.Split('.');
    var currentObj = formattedDictionary;
    for (int i = 0; i < parts.Length - 1; i++)
    {
        var property = parts[i];


        int index = -1;
        //naive handle arrays
        if (property.Contains('['))
        {
            var bits = property.Split('[', ']');
            property = bits[0];
            index = int.Parse(bits[1]);
        }


        if (!currentObj.ContainsKey(property))
        {
            //is it an array
            if (index > -1)
            {
                //make a list of dictionaries instead of just one
                var list = new List<Dictionary<string, object>>();
                currentObj[property] = list;

                //ensure there are enough list entries for us to access the list by index without it going boom
                while (list.Count <= index)
                    list.Add(new Dictionary<string, object>());

                //"travel" to the current obj being the list item, at index whatever            
                currentObj = (Dictionary<string, object>)list[index];
            }
            else {
                currentObj[property] = new Dictionary<string, object>();
                currentObj = (Dictionary<string, object>)currentObj[property];
            }
        }
                    
    }

    currentObj[parts[^1]] = pair.Value;
}

I haven't tested it, but it basically extends the "create a new sub dictionary" to be "if it contains an indexer then it must be a list so ensure there is a list big enough to hold it, and travel to that list index instead"我还没有测试过,但它基本上将“创建一个新的子字典”扩展为“如果它包含一个索引器,那么它必须是一个列表,因此确保有一个足够大的列表来容纳它,然后前往该列表而是索引”

Just be aware that the object in the formattedDictionary is no longer always a string, or a Dictionary.请注意,formattedDictionary 中的 object 不再总是字符串或字典。 It might now sometimes be a List<Dictionary> too现在有时也可能是List<Dictionary>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM