-3

I have a requirement to convert a JSON file into C# Class and to create a C# Class at a specific folder in the system.

For ex:

{ "id": "string", "fullName": "string" }

This JSON can change during run time.I need to convert this into C# Class like

 public class Root    {
    public string id { get; set; } 
    public string fullName { get; set; } 

}

Then I need to write this class into.cs file inside any location in the system. Any help is appreciated

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Gokul Vijayan
  • 105
  • 1
  • 11
  • 2
    Where is your code, which you've tried? – Pavel Anikhouski Jul 24 '20 at 09:47
  • 3
    C# is statically-typed, you can't meaningfully create new types at runtime. Please think things through about what you actually need to achieve. – Dai Jul 24 '20 at 09:48
  • You want to create a class in. Cs file and then I use it in the same project as the current code is running? – Chetan Jul 24 '20 at 09:50
  • No, I just want to create a class in. Cs file in a location specified by me – Gokul Vijayan Jul 24 '20 at 09:53
  • To rule out any language or terminology problems, maybe you can explain why you need this and how you would use it? – TheGeneral Jul 24 '20 at 09:56
  • I need to check the response of some API's using Rest Sharp. I don't want to create a class beforehand for deserializing the JSON to object of the Class. Instead, I want to create the class during run time and store the class in a.Cs file from which I used the class for deserializing the JSON – Gokul Vijayan Jul 24 '20 at 10:04
  • Does this answer your question? [How to dynamically create a class?](https://stackoverflow.com/questions/3862226/how-to-dynamically-create-a-class) – pi-di-tredipi Jul 28 '20 at 12:06

1 Answers1

0

Well, if you do not know how to use reflection then do not use it. Especially if you do not need to load the class definition into the executing process.

What you could do is just process the json object with a library, token by token and write everything into a .cs file. These classes are simple enough that you do not need much work. A few switch statements should do the trick, the rest could be constant strings.

I recommend trying out the good old Newtonsoft.Json library: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JTokenReader.htm You can iterate through the document, switch on the type and then use some string magic to put the properties together.