Created
February 8, 2018 11:53
-
-
Save mcintyre321/f565869c452a3ffd00bfdad2f14f093f to your computer and use it in GitHub Desktop.
FormCollection to JObject extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class FormCollectionToJObjectExtension | |
{ | |
public static JObject ToJObject(this IFormCollection form) | |
{ | |
JObject target = new JObject(); | |
foreach (var element in form) | |
{ | |
Add(target, element.Key, element.Value); | |
} | |
return target; | |
void Add(JObject jo, string key, StringValues value) | |
{ | |
var chars = new[] { '.', '[' }; | |
var x = key.IndexOfAny(chars); | |
if (x == -1) | |
jo[key] = value.LastOrDefault(); | |
else | |
{ | |
var name = key.Substring(0, x); | |
if (key[x] == '.') | |
{ | |
var subJo = jo[name] as JObject ?? (JObject)(jo[name] = new JObject()); | |
Add(subJo, key.Substring(x + 1), value); | |
} | |
else | |
{ | |
var subJa = jo[name] as JArray ?? (JArray)(jo[name] = new JArray()); | |
var closeBracketsIndex = key.IndexOf(']', x + 1); | |
var itemIndex = int.Parse(key.Substring(x + 1, closeBracketsIndex - x - 1)); | |
while (subJa.Count < itemIndex + 1) subJa.Add(null); | |
if (closeBracketsIndex == key.Length - 1) | |
{ | |
subJa[itemIndex] = value.LastOrDefault(); | |
return; | |
} | |
if (key[closeBracketsIndex + 1] != '.') throw new Exception(); | |
var remainder = key.Substring(closeBracketsIndex + 2); | |
var subJo = subJa[itemIndex] as JObject ?? (JObject)(subJa[itemIndex] = new JObject()); | |
Add(subJo, remainder, value); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment