This is what I tried with Linq GroupBy and worked as expected:
using Newtonsoft.Json;
using System;
using System.Linq;
namespace SampleConsoleApp
{
internal class Program
{
static void Main(string[] args)
{
var json = @"
[
{make: ""Chevy"", model: ""2500"", location: ""lot""},
{make: ""Ford"", model: ""Edge"", location: ""lot""},
{make: ""Chevy"", model: ""1500"", location: ""lot""},
{make: ""Chevy"", model: ""Econoline"", location: ""back lot""},
{make: ""GMC"", model: ""Acadia"", location: ""back lot""},
{make: ""GMC"", model: ""Terrain"", location: ""in transit""},
{make: ""Chevy"", model: ""Cruze"", location: ""in transit""},
{make: ""Ford"", model: ""F150"", location: ""ordered""}
]";
var structure = new[] { new { make = "", model = "", location = "" } };
var data = JsonConvert.DeserializeAnonymousType(json, structure).ToArray();
var tree = data.GroupBy(x => x.make)
.Select(g => new
{
text = g.Key,
nodes = g.GroupBy(xx => xx.location)
.Select(gg => new
{
text = gg.Key,
nodes = gg.Select(xxx => new { text = xxx.model })
})
.ToArray()
}).ToArray();
Console.WriteLine(JsonConvert.SerializeObject(tree, Formatting.Indented));
Console.ReadLine();
}
}
}
Which prints out data:
[
{
"text": "Chevy",
"nodes": [
{
"text": "lot",
"nodes": [
{
"text": "2500"
},
{
"text": "1500"
}
]
},
{
"text": "back lot",
"nodes": [
{
"text": "Econoline"
}
]
},
{
"text": "in transit",
"nodes": [
{
"text": "Cruze"
}
]
}
]
},
{
"text": "Ford",
"nodes": [
{
"text": "lot",
"nodes": [
{
"text": "Edge"
}
]
},
{
"text": "ordered",
"nodes": [
{
"text": "F150"
}
]
}
]
},
{
"text": "GMC",
"nodes": [
{
"text": "back lot",
"nodes": [
{
"text": "Acadia"
}
]
},
{
"text": "in transit",
"nodes": [
{
"text": "Terrain"
}
]
}
]
}
]