使用JSon.net将平面JSON数据反序列化为结构

时间:2012-07-20 16:09:48

标签: c# .net json.net

我正在使用返回JSON数据的Web服务,并且在很多情况下,服务会在一个对象中返回几个属性,我想将它们分组到C#端的类中。考虑一个类结构,如:

  class Person
  {
      public Address Address { get; set; }
      public string Name {  get; set; }
  }

  class Address
  {
      public string StreetAddress { get; set; }
      public string City {  get; set; }
      public string ZipCode {  get; set; }
  }

和JSON数据一样:

{ "Name" : "Pilchie",
"StreetAddress" : "1234 Random St",
"City" : "Nowheretown",
"Zip" : "12345"
}

是否可以归因于我的PersonAddress类,以便它们序列化/反序列化为此格式?

4 个答案:

答案 0 :(得分:2)

我认为你不能让JSON.NET一次性完成这一切 - 你必须手动创建Person对象。但是,您可以在不创建单独的DTO类的情况下完成此操作。例如:

var jsonText = "{ \"Name\" : \"Pilchie\"," +
            "\"StreetAddress\" : \"1234 Random St\"," +
            "\"City\" : \"Nowheretown\"," +
            "\"Zip\" : \"12345\"" +
            "}";
JObject jsonObject = (JObject) JsonConvert.DeserializeObject(jsonText);

var person =
    new Person
    {
        Address = new Address
                    {
                    City = (String) jsonObject["City"],
                    StreetAddress = (String) jsonObject["StreetAddress"],
                    ZipCode = (string) jsonObject["Zip"]
                    },
        Name = (string) jsonObject["Name"]
    };

序列化:

JsonConvert.SerializeObject(
    new
    {
        person.Name,
        person.Address.StreetAddress,
        person.Address.City,
        Zip = person.Address.ZipCode
    });

答案 1 :(得分:0)

我认为,对您正在使用的数据进行反序列化的最简单方法是创建一个与JSON数据格式匹配的简单DTO对象。然后,您可以使用AutoMapper或类似的库轻松地将数据映射到新结构。

答案 2 :(得分:0)

这完全取决于您将如何使用数据。如果您只想访问地址属性,可以执行以下操作:

class Person
{
    public string Name { get; set; }
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }

    [ScriptIgnore]
    public Address Address { get {return new Address(){StreetAddress = this.StreetAddress,
                                                       City = this.City,
                                                       ZipCode = this.ZipCode} } }
}

答案 3 :(得分:0)

var person = JsonConvert.DeserializeObject<Person>(json);

class Person
{
    [JsonProperty("StreetAddress")]
    private string _StreetAddress { get; set; }

    [JsonProperty("City")]
    private string _City { get; set; }

    [JsonProperty("Zip")]
    private string _ZipCode { get; set; }

    public string Name { get; set; }

    public Address Address
    {
        get
        {
            return new Address() { City = _City, StreetAddress = _StreetAddress, ZipCode = _ZipCode };
        }
    }
}

class Address
{
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
}