问题
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:
Generate C# classes from JSON Schema Is asking about JSON Schemas which may be an approach to use down the road.
Benefits and drawbacks of generated C# classes for Json objects
回答1:
Four options:
Use the free json2csharp web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io (available in a link from json2csharp) also does not require installing anything.
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.
回答2:
Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.
Visual Studio 2013 onwards have this built-in.
(Image courtesy: robert.muehsig)
回答3:
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/
来源:https://stackoverflow.com/questions/21611674/how-to-auto-generate-a-c-sharp-class-file-from-a-json-string