将Json反序列化到类

本文关键字:反序列化 Json | 更新日期: 2023-09-27 18:14:12

如果我有JSON文件

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

,我想使用序列化器。我明白我需要创建一个适合JSON类别的类。

所以我创建了这个:

class Person
{
    public String firstName;
    public String lastName;
    public String age;
    public class address
    {
        public String streetAddress;
        public String city;
        public String state;
        public String postalCode;
    }
    public class phoneNumber
    {
        public String type;
        public String number;
    }
}

它可以很好地处理年龄和姓名,但不能处理address和phoneNumber(我不知道如何在类文件中创建它们)。我希望你能帮助我。

将Json反序列化到类

Via http://json2csharp.com/

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 Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public int age { get; set; }
    public Address address { get; set; }
    public List<PhoneNumber> phoneNumber { get; set; }
}

您没有为地址和电话号码创建属性。必须有一个目标属性才能将数据放入该属性

像这样:

class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public int age { get; set; }
    public Address address { get; set; } // here
    public IEnumerable<PhoneNumber> phoneNumber { get; set; } // and here
    public class Address { /.../ }
    public class PhoneNumber { /.../ }
}

使用getter和setter

public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public int age { get; set; }
public Address address { get; set; }
}
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; }
}