2015-06-24 26 views
0

嗨,我有以下代碼從一個REST服務數據:Asp.NET HttpClient的定製JsonConverter

HttpResponseMessage response; 
        response = client.GetAsync("CatalogUpdate/" + sessionId).Result; 

        if (response.IsSuccessStatusCode) 
        { 
         catalogs = response.Content.ReadAsAsync<List<Models.CatalogInfo>>().Result; 
        } 

我CatalogInfo類是:

public class CatalogInfo 
    { 
     public CatalogInfo(int id,string name,string date) 
     { 
      this.ID = id; 
      this.Name = name; 
      this.Date = date; 

     } 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public string Date { get; set; } 

    } 

並且json,即時通訊從得到REST服務是:

{"error":false,"locations":[{"ID":"3","ABC":"XC","Description":"Rome","Status":"1"},{"ID":"4","CD1":"XH","Description":"Italy","Status":"1"}]} 

我想將JSON映射到我的CatalogInfo類,是有T A方式o這樣做?

+0

你怎麼想*地圖*考慮到他們有不同的屬性,似乎無關? – Lloyd

+0

我想用ID和名稱來映射ID – VAAA

+0

這個[問題] [1]看起來與您正在尋找的相似。 [1]:http://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object – Anushree

回答

1

這裏最簡單的方法是使用Json.NET和創建代表預期JSON類,因此,例如:

class Location 
{ 

    public string ID { get; set; } 
    public string Description { get; set; } 
} 

class JSONResponse 
{ 

    [JsonProperty("error")] 
    public bool Error { get; set; } 

    [JsonProperty("locations")] 
    public Location[] Locations { get; set; } 

} 

我們並沒有實現所有的財產Json.NET將只忽略那裏不存在的東西。

然後反序列化響應。在你的情況你使用HttpResonseMessage所以是這樣的:

JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(
    await response.Content.ReadAsStringAsync() 
); 

然後可以使用LINQ到的位置轉換到你的對象:

CatalogInfo[] catalog = response.Locations.Select(loc => new CatalogInfo(
    loc.ID, 
    loc.Description, 
    String.Empty 
)).ToArray();