I have code that extracts the Namespace, Classes, Methods and parameters from the user defined dll file.
I need a code that can serialize Namespace, Classes, Methods and Parameters in JSON.
=================== C# Code
public static void Main(string[] args)
{
string filePath = @"C:\Users\admin\source\repos\TestHarness\UtilityFunctions\bin\Debug\netstandard2.0\UtilityFunctions.dll";
if (File.Exists(filePath))
{
Assembly SampleAssembly = Assembly.LoadFrom(filePath);
Type[] types = SampleAssembly.GetTypes();
foreach (var type in types)
{
string tChoice = type.ToString();
Console.WriteLine(tChoice);
MethodInfo[] methods = type.GetMethods();
foreach (var method in methods)
{
Console.WriteLine("Class: " +type.Name+"\n"+ "Method: "+method.Name);
ParameterInfo[] parameters = method.GetParameters();
foreach (var param in parameters)
{
Console.WriteLine("Parameter:"+param.Name+":"+param.ParameterType);
}
var countP = parameters.Count();
Console.WriteLine(" -- Total Parameters:" + countP);
}
var countC = types.Count();
string testString = "BasicMathFunctions";
for (int i = 0; i < countC; i++)
{
if (testString == types[i].Name)
{
Type typeChoice = types[i];
string methodChoice = "MultiplyOperation";
dynamic dObj = Activator.CreateInstance(typeChoice);
var methodInfo = typeChoice.GetMethod(methodChoice);
object[] parametersArray = new object[] { 15, 10 };
var result = methodInfo.Invoke(dObj, parametersArray);
Console.WriteLine("Result: " + result);
Console.ReadKey();
}
}
=== Expected JSON format
[{
"namespace": "namespace1",
"classes": {
"classname": "math1",
"methods": {
"methodname": "m1",
"params": {
"seq": "1",
"paramname": "",
"paramtype": ""
}
},
"classname": "math2",
"methods": {
"methodname": "m1",
"params": {
"seq": "1",
"paramname": "",
"paramtype": ""
}
}
},
}, {
"namespace": "alternatenamespace1",
"classes": {
"classname": "math1",
"methods": {
"methodname": "m1",
"params": {
"seq": "1",
"paramname": "",
"paramtype": ""
}
},
"classname": "math2",
"methods": {
"methodname": "m1",
"params": {
"seq": "1",
"paramname": "",
"paramtype": ""
}
}
},
}
]
What I have tried:
I was able to get json format for the list:
var opt = new JsonSerializerOptions() { WriteIndented = true };
string strJson = JsonSerializer.Serialize<Department>(dept, opt);
However I am still not able to apply this code to my above code.
Can anyone please help?