表示JSON数据的c#类

本文关键字:数据 JSON 表示 | 更新日期: 2023-09-27 18:02:44

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"
          }]
}

表示JSON数据的c#类

您可以使用这样的站点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; }
}

您可以使用类似http://json2csharp.com/的服务将其转换。输入JSON,它就会输出c#模型类。然后,将它们作为类或使用实体框架(取决于您的目标)添加到您的项目中。

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