4

我正在使用一个返回 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"
}

是否可以将 myPersonAddressclasses 属性化,以便它们序列化/反序列化为这种格式?

4

4 回答 4

3

我不认为您可以让 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
    });
于 2012-07-20T17:04:22.433 回答
0

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

于 2012-07-20T16:15:17.453 回答
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; }
}
于 2012-07-20T17:09:49.440 回答
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} } }
}
于 2012-07-20T16:30:28.350 回答