How to Convert JSON to a Class in C#

I have been working on .Net projects where I need to work with JSON to a class in C#. I came across a web site created by Jonathan Keith using the popular JSON.Net library by James Newton-King.

The web site allows me to copy and paste JSON code to a form and by pressing the generate button I was able to get back a class that I can copy and use in my .Net project. This web site is very useful to me since I am also using the JSON.Net library in my current project to Deserialise JSON data in to an object.

http://json2csharp.com

json2csharp_web

C#: Interface

What is an interface?

Interface is a similar to a class it can contain properties, methods, events and indexers. Each member in an interface must have the public access modifier, and other access modifiers will not work with an interface. Interface do not contain any implementations, the only way to use an interface is by creating a subclass that implements the interface members.

public interface IDisplayMessage {
   public void Show();
}

How do you use an interface?

To use an interface you must create a subclass that inherits the interface and implement it’s members. For example below I have created a subclass called MyClass the implements the IDisplayMessage interface and it’s members. Inside the Show() method I write my own piece of code to output a text message to the console:

public class MyClass : IDisplayMessage {
   private string message;
   public MyClass() {
      message = "Hello, World!";
   }
   public void Show() {
      Console.WriteLine(message);
   }
}
void Main() {
   MyClass myClass = new MyClass();
   myClass.Show();
}

You can implicitly cast an object to any interface that it implements. For example below I am casting myClass to IDisplayMessage and still will be able to call the Show() method.

   IDisplayMessage displayMessage = new MyClass();
   displayMessage.Show();

Summary

Interface is similar to a class, it contains public properties and methods with no implementation. Subclass my using an interface must implement all the members and object can be implicitly cast to an interface that it implements.

 

 

Shares