2012-07-20 69 views
4

我消費web服務返回JSON數據,並在許多情況下,服務會返回一個對象的幾個屬性,我想組到C#的側類。考慮一類結構,如:反序列化JSON平數據轉換成結構JSon.net

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類,以使其序列化/反序列化爲這種格式?

+0

與結構/字段創建一個DTO命名你想,然後使用與json.net。 – 2012-07-20 16:13:04

回答

0

我認爲最簡單的方法來反序列化,你就吃下會創建一個JSON數據的格式相匹配的簡單的DTO對象中的數據。然後,您可以使用AutoMapper或類似的庫輕鬆地將數據映射到新結構。

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

我不認爲你可以得到JSON.NET做這一切在一杆 - You'll必須創建人員對象手動。但是,您可以在不創建單獨的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 
    }); 
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; } 
}