public with sharing class Celestial {
public string jsonString {get;set;}
public List<User__c> userList {get;set;}
public List<mainWrapper> jsonList = new List<mainWrapper>();
public Celestial() {
userList = [select id, Name, Reports_To__c, Position__c from User__c ];
mainWrapper mw = new mainWrapper();
mw.name = 'Chris C';
mw.position = 'Charmain ';
mw.adjacencies = new List<childWrapper>();
jsonList.add(mw);
List<User__c> users = childPeopleByPosition('CIO');
for(User__c u1 : users )
{
childWrapper cObj1 = new childWrapper();
cObj1.nodeTo = u1.Id;
mw.adjacencies.add(cObj1);
mainWrapper mw1 = new mainWrapper ();
mw1.id = u1.Id;
mw1.name = u1.Name;
mw1.position = u1.Position__c;
mw1.adjacencies = new List<childWrapper>();
jsonList.add(mw1);
List<User__c> users1 = new List<User__c>();
users1 = childPeopleById(mw1.Id);
for(User__c u2 : users1 )
{
childWrapper cObj2 = new childWrapper();
cObj2.nodeTo = u2.Id;
mw1.adjacencies.add(cObj2);
mainWrapper mw2 = new mainWrapper();
mw2.id = u2.Id;
mw2.name = u2.Name;
mw2.position = u2.Position__c;
mw2.adjacencies = new List<childWrapper>();
jsonList.add(mw2);
List<User__c> users2 = new List<User__c>();
users2 = childPeopleById(mw2.Id);
for(User__c u3 : users2 )
{
childWrapper cObj3 = new childWrapper();
cObj3.nodeTo = u3.Id;
mw2.adjacencies.add(cObj3);
mainWrapper mw3 = new mainWrapper();
mw3.id = u3.Id;
mw3.name = u3.Name;
mw3.position = u3.Position__c;
mw3.adjacencies = new List<childWrapper>();
jsonList.add(mw3);
List<User__c> users3 = new List<User__c>();
users3 = childPeopleById(mw3.Id);
for(User__c u4 : users3 )
{
childWrapper cObj4 = new childWrapper();
cObj4.nodeTo = u4.Id;
mw3.adjacencies.add(cObj4);
mainWrapper mw4 = new mainWrapper();
mw4.id = u4.Id;
mw4.name = u4.Name;
mw4.position = u4.Position__c;
mw4.adjacencies = new List<childWrapper>();
jsonList.add(mw4);
List<User__c> users4 = new List<User__c>();
users4 = childPeopleById(mw4.Id);
for(User__c u5: users4 )
{
childWrapper cObj5 = new childWrapper ();
cObj5.nodeTo = u5.Id;
mw4.adjacencies.add(cObj5);
mainWrapper mw5 = new mainWrapper();
mw5.id = u5.Id;
mw5.name = u5.Name;
mw5.position = u5.Position__c;
jsonList.add(mw5);
}
}
}
}
}
System.debug(jsonList);
jsonString = JSON.serialize(jsonList);
}
public List<User__c> childPeopleByPosition (String position)
{
List<User__c> childList = new List<User__c>();
for(User__c p: userList )
{
if (p.Position__c == position )
{
childList.add(p);
}
}
return childList;
}
public List<User__c> childPeopleById (Id parentId)
{
List<User__c> childList = new List<User__c>();
for(User__c p: userList )
{
if (p.Reports_To__c == parentId )
{
childList.add(p);
}
}
return childList;
}
public class mainWrapper
{
public String name;
public String id;
public String position;
public List<childWrapper> adjacencies;
}
public class childWrapper
{
public string nodeTo;
}
}