How about something simple like:
public class ReflectedPropertyInfo
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public class ReflectJson
{
public static string ReflectIntoJson<T>() where T : class
{
var type = typeof(T);
var className = type.Name;
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propertyList = new List<ReflectedPropertyInfo>();
foreach (var prop in props)
{
propertyList.Add(new ReflectedPropertyInfo{Key =prop.Name, Type =prop.PropertyType.Name});
}
var result = JsonConvert.SerializeObject(new {@class = className, parameters = propertyList}, Formatting.Indented);
return result;
}
}
It uses Reflection, as suggested by @dbc. After getting the type name, it gets a collection of properties and then builds up a anonymous type containing the information in the correct format, and then serializes it. The result looks like:
{
"class": "SectionD",
"parameters": [
{
"key": "InsertID",
"type": "String"
},
{
"key": "CaseReference",
"type": "Int32"
},
{
"key": "AdditionalInfo",
"type": "String"
},
{
"key": "CreationDate",
"type": "DateTime"
}
]
}
The only difference (that I see) is that it uses the actual "Int32" as the type name for integers, rather than the C# alias "int".
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…