2015-04-02 47 views
0

我有一個C#應用程序,一旦你按下按鈕,它會發送一個Web請求到Web API並檢索所有的Json值。然後這些被反序列化成一個對象並返回到函數被調用的地方。如何從不同的功能和類別訪問返回的對象

現在我試圖訪問從另一個類中的GetApi函數返回的對象。

無法將類型'object'隱式轉換爲'GW2_tradingPost.Listings'。 的顯式轉換存在(是否缺少強制轉換?)線32

我明白我做錯了,但我無法掌握什麼是怎麼了。

Form1.cs的

private void button1_Click(object sender, EventArgs e) 
    { 
     Listings Listings = new Listings(); 
     api_Request api_Request = new api_Request(); 

     Listings richTextBox1 = api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings/19684"); 
    } 

api_Request.cs使用這個現在在目標物體上打電話,在MessageBox返回值

public class api_Request 
    { 
     public Object GetApi(string url) 
     { 

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 

      try 
      { 
       WebResponse response = request.GetResponse(); 
       using (Stream responseStream = response.GetResponseStream()) 
       { 
        //StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); 
        //return reader.ReadToEnd(); 
        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); 
        var jsonReader = new JsonTextReader(reader); 
        var serializer = new JsonSerializer(); 
        return serializer.Deserialize<Listings>(jsonReader); 
       } 
      } 
      catch (WebException ex) 
      { 
       WebResponse errorResponse = ex.Response; 
       using (Stream responseStream = errorResponse.GetResponseStream()) 
       { 
        StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); 
        String errorText = reader.ReadToEnd(); 
        // log errorText 
       } 
       throw; 
      } 
     } 

    } 

    public class Listings 
    { 
     [JsonProperty(PropertyName = "id")] 
     public int Id { get; set; } 

     public List<Buy> Buys { get; private set; } 

     public Listings() 
     { 
      Buys = new List<Buy>(); 
     } 
    } 
    public class Buy 
    { 
     [JsonProperty(PropertyName = "listings")] 
     public int Listings { get; set; } 

     [JsonProperty(PropertyName = "unit_price")] 
     public int UnitPrice { get; set; } 

     [JsonProperty(PropertyName = "quantity")] 
     public int Quantity { get; set; } 
    } 

IM,但它返回0,這應該是19684。

api_Request.GetApi(「https://api.guildwars2.com/v2/commerce/listings/19684」); MessageBox.Show(Listings.Id.ToString());

回答

1

您的簽名是Object GetApi(string url)。將其更改爲Listings GetApi(string url),因爲這是您實際從該方法返回的結果。

另外考慮給「GetApi」方法一個更明智的名字,告訴它實際上做了什麼。

+0

好吧,這實際上返回正確的類型很有意義。但是如何。但爲了訪問對象,我該怎麼做?現在它返回類名'Listings'作爲即時消息不說我想從對象檢索。 – 2015-04-02 13:40:43

+0

@Krijn我不確定你的意思,但是班上有你可以訪問的屬性。 – CodeCaster 2015-04-02 13:51:49

+0

是的,我正要回應,我得到它的工作,對不起!只是一些愚蠢的語法,我不斷搞亂。非常感謝幫助我! – 2015-04-02 13:53:50