将Json反序列化为类

时间:2016-10-20 13:34:15

标签: c# json visual-studio visual-c++

如果我有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;
    }

}

它适用于年龄和名称,但没有地址和phoneNumber(我不知道如何在类文件中创建它们)。 我希望你能帮助我。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

这样的事情:

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 { /.../ }
}

答案 2 :(得分:0)

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