How to auto-generate a C# class file from a JSON string

C#JsonCode Generation

C# Problem Overview


Given the following JSON object,

form = {
  "name": "",
  "address": {
    "street": "",
    "city": "",
    "province": "",
    "postalCode": "",
    "country": ""
  },
  "phoneDay": "",
  "phoneCell": "",
  "businessName": "",
  "website": "",
  "email": ""
}

what is a tool to auto-generate the following C# class?

public class ContactInfo
{
    public string Name { get; set; }
    public Address Address { get; set; }
    public string PhoneDay { get; set; }
    public string PhoneCell { get; set; }
    public string BusinessName { get; set; }
    public string Website { get; set; }
    public string Email { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Province { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
}

We have already looked at these questions:

https://stackoverflow.com/questions/6358745/generate-c-sharp-classes-from-json-schema Is asking about JSON Schemas which may be an approach to use down the road.

https://stackoverflow.com/questions/9229237/benefits-and-drawbacks-of-generated-c-sharp-classes-for-json-objects

C# Solutions


Solution 1 - C#

Five options:

Pros and Cons:

  • jsonclassgenerator converts to PascalCase but the others do not.

  • app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

Solution 2 - C#

Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.

Visual Studio 2013 onwards have this built-in.

Visual Studio Paste JSON as Classes screenshot (Image courtesy: robert.muehsig)

Solution 3 - C#

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShaun LuttinView Question on Stackoverflow
Solution 1 - C#Shaun LuttinView Answer on Stackoverflow
Solution 2 - C#MrchiefView Answer on Stackoverflow
Solution 3 - C#KennethView Answer on Stackoverflow