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



我正在使用一个返回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类赋予属性,以便它们序列化/反序列化为这种格式?

我不认为您可以让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
    });

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

这一切都取决于您将如何使用数据。如果你只想访问一个地址属性,你可以这样做:

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

相关内容

  • 没有找到相关文章

最新更新