如何在C# Visual Studio中将JSON文本转换为类对象[复制]

dldeef67  于 2023-04-22  发布在  C#
关注(0)|答案(1)|浏览(243)

此问题已在此处有答案

How to convert JSON to C# classes?(5个答案)
6天前关闭.

{
  "firstName": "John",
  "lastName": "Smith",
  "gender": "man",
  "age": 32,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "fax",
      "number": "646 555-4567"
    }
  ]
}

我想直接创建对象或类,而不是手动逐个编写C#属性,如:

public string firstName{ get; set; }
        public string lastName{ get; set; }
af7jpaap

af7jpaap1#

有一些方便的工具,在那里照顾你所问的。你只需要做一些搜索在线。我已经在过去使用这个网站,它是相当不错的:
json2csharp.com
你将JSON片段粘贴到一个面板中并转换它,它会给出以下输出:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Address
{
    public string streetAddress { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string postalCode { get; set; }
}

public class PhoneNumber
{
    public string type { get; set; }
    public string number { get; set; }
}

public class Root
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string gender { get; set; }
    public int age { get; set; }
    public Address address { get; set; }
    public List<PhoneNumber> phoneNumbers { get; set; }
}

你可能需要做一些调整,但我认为它基本上做到了你想要的。

相关问题