The issue with building a string here is you have to ensure that the syntax is 100% correct, opening and closing braces, adding commas etc. All possible but quite a hassle.
A solution to avoid magic strings altogether is to use LINQ-to-XML as an intermediary translation step. Like this:
public static class NestedStaticClassWithStringPropertiesJsoniser
{
public static string GetJson(this Type type)
{
XElement rootXml = new XElement(type.Name);
XElement xmlContent = CreateXmlTree(rootXml, type);
string jsonString = JsonConvert.SerializeXNode(xmlContent);
return jsonString;
}
public static XElement CreateXmlTree(XElement parent, Type type)
{
AddStringProperties(parent, type);
AddNestedClasses(parent, type);
return parent;
}
private static void AddNestedClasses(XElement parent, Type type)
{
var subTypes = type.GetNestedTypes();
foreach (var subType in subTypes)
{
var newElement = new XElement(subType.Name);
var subTree = CreateXmlTree(newElement, subType);
parent.Add(subTree);
}
}
private static void AddStringProperties(XElement parent, Type type)
{
var properties = type.GetFields();
foreach (var property in properties)
{
var propertyElement = new XElement(property.Name);
propertyElement.SetValue(property.GetValue(null));
parent.Add(propertyElement);
}
}
}
It can easily be used like this:
string json = typeof(ATypeWithNestedStaticClasses).GetJson();