代表JSON数据的C#类

时间:2016-08-17 18:08:13

标签: c# json json.net

C#类定义在表示此JSON数据时会是什么样的?

{
        "accountId": "101",
        "website": "www.example.com",
        "alternateWebsites": [
          {
            "website": "site2.example.com"
          }
        ],
        "email": "contact@mysite.com",
        "alternateEmails": [
          {
            "email": "sales@example.com"
          }
        ],
        "address": {
           "street": "234 Main Street",
           "city": "San Diego",
           "postalCode": "92101",
           "state": "CA"
         },
        "rankingKeywords": 
         [{
            "keyword": "Coffee",
            "localArea": "Sacramento, CA"
          }]
}

2 个答案:

答案 0 :(得分:4)

您可以使用此类http://jsonutils.com/

这样的网站

你粘贴在你的json中,它会为你构建你的类。你的JSON产生的结果......

public class AlternateWebsite
{
    public string website { get; set; }
}

public class AlternateEmail
{
    public string email { get; set; }
}

public class Address
{
    public string street { get; set; }
    public string city { get; set; }
    public string postalCode { get; set; }
    public string state { get; set; }
}

public class RankingKeyword
{
    public string keyword { get; set; }
    public string localArea { get; set; }
}

public class Root
{
    public string accountId { get; set; }
    public string website { get; set; }
    public IList<AlternateWebsite> alternateWebsites { get; set; }
    public string email { get; set; }
    public IList<AlternateEmail> alternateEmails { get; set; }
    public Address address { get; set; }
    public IList<RankingKeyword> rankingKeywords { get; set; }
}

答案 1 :(得分:3)

您可以使用http://json2csharp.com/之类的服务进行转换。输入JSON,它将吐出C#模型类。然后,将它们作为类添加,或者使用Entity Framework(取决于您的目标)添加到项目中。

C#版本:

public class AlternateWebsite
    {
        public string website { get; set; }
    }

public class AlternateEmail
{
    public string email { get; set; }
}

public class Address
{
    public string street { get; set; }
    public string city { get; set; }
    public string postalCode { get; set; }
    public string state { get; set; }
}

public class RankingKeyword
{
    public string keyword { get; set; }
    public string localArea { get; set; }
}



public class RootObject
{
    public string accountId { get; set; }
    public string website { get; set; }
    public List<AlternateWebsite> alternateWebsites { get; set; }
    public string email { get; set; }
    public List<AlternateEmail> alternateEmails { get; set; }
    public Address address { get; set; }
    public List<RankingKeyword> rankingKeywords { get; set; }
}