2014-02-06 155 views
63

一個C#類文件,如何自動生成考慮下面的JSON對象JSON對象字符串

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

什麼是一個工具自動生成下面的C#類?

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; } 
} 

我們已經看了這些問題:

Generate C# classes from JSON Schema詢問有關JSON架構可能是使用的道路的一種方法。

Benefits and drawbacks of generated C# classes for Json objects

+3

http://json2csharp.com/ ??? – Habib

+0

試試這個工具可能會有所幫助.. http://tools4geeks.com/json-to-Csharp-classes –

回答

99

三個選項:

優點和缺點:

+0

Web Essentials和json2csharp都做得很好。沒有嘗試jsonclassgenerator,導致它看起來像一個麻煩,需要打開一個單獨的應用程序只爲了 –

+1

我還沒有嘗試過jsonclassgenerator,但我可以看到優勢。例如,如果你有一個模擬API,你可以通過一組端點來重新生成你的模型。您可以儘可能設置一個腳本來檢查新的提交,並在有更改的情況下更新模型。您不希望每次都手動粘貼新的json,因爲這可能容易出錯。 –

+0

json2csharp工具比VS格式化類更好,尤其是類名格式。它將刪除諸如「_」之類的含糊不清的字符,並在此後正確地使用類名。 –

8

如果您將Web Essentials安裝到Visual Studio中,您可以前往Edit => Past special =>粘貼JSON作爲類。

這可能是最簡單的。

網絡要點:http://vswebessentials.com/

67

的Visual Studio 2012(與ASP.NET和Web Tools安裝2012.2 RC)支持此natively

Visual Studio 2013以上版本具有此內置功能。

Visual Studio Paste JSON as Classes screenshot (圖片提供:robert.muehsig

+3

我認爲這個解決方案是最好的,因爲你不需要外部程序! –

+0

+1我比較喜歡這個答案。誰會希望第三方工具可以在VS中使用此功能;) – Bharath

+0

粘貼之前[here](http://superuser.com/questions/777213/copy-json-from-console-log-in-developer-tool - 從剪貼板)是**解決方案將JSON從開發人員工具中的console.log **複製到剪貼板。希望有幫助。 – stom