Convert string with dot notation to JSON Asp.Net
Issue-
You might have faced issue converting string with dot notation to JSON Asp.Net. Have a look at this image
So as in the image you can see we have dot separated hierarchy which we have to convert in json. So we will have a look at how to do that in c#.
Step-1
So we will start by creating a class for our hierarchical data
public class Treepath
{
public string Key { get; set; }
public Treepath children { get; set; }
}
Now you can use this piece of code for converting your dot notation to JSONList<Treepath> trees = new List<Treepath>();
foreach (var path in treepath)
{
var item = new Treepath();
var sublevel = path.Split(".");
for (int i = 0; i < 1; i++)
{
var lastitem = new Treepath();
for (int j = sublevel.Count()-1; j > 0; j--)
{
if (sublevel[j] == sublevel.LastOrDefault())
{
lastitem.children = new Treepath { Key = sublevel[j], children = null };
}
else
{
lastitem.children = new Treepath { Key = sublevel[j], children = lastitem.children };
}
}
lastitem.Key = sublevel[i];
item = lastitem;
}
trees.Add(item);
}
var json = JsonConvert.SerializeObject(trees);