我有这个代码,它从Api链接中检索Json值并将它们输入到列表中。在此列表中有ID,如果存在于另一个API链接中,则会检查所有这些ID。
private void button1_Click(object sender, EventArgs e)
{
var spidyApi_searchIdByName_result = api_Handler.GetApi(spidyApi_searchIdByName);
var Gw2Api_isItemIdinListing_result = api_Handler.GetApi(Gw2Api_allListings + spidyApi_searchIdByName_result.???); // can't access object property
}
这是GetApi方法:
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);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<RootObject>(jsonReader);
}
}
catch (WebException)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<A>("{\"text\":\"no such id\"}");
}
}
这是GetApi()
方法反序列化的RootObject:
public class RootObject
{
public int id { get; set; }
// ...
}
但是,从object
返回GetApi()
时,我无法访问返回的对象的属性。我怎样才能访问这些?
答案 0 :(得分:0)
你有两个问题。
首先,您从方法中返回object
,因此无法访问any members that object
doesn't have。这就是为什么你应该返回一个更专业的类型like I already advised,所以在这种情况下:
public RootObject GetApi(string url)
{
// ...
return serializer.Deserialize<RootObject>(jsonReader);
}
但是,您希望此方法能够执行更多操作。您希望从中返回两种类型,并添加错误处理。
泛型(参见T
)可以在这里提供帮助,您可以在调用方法时指定类型:
public T GetObjectFromApi<T>(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);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<T>(jsonReader);
}
}
catch (WebException)
{
return null;
}
}
然后这样称呼:
var spidyApi_searchIdByName_result = api_Handler.GetObjectFromApi<spidyApiResult>(spidyApi_searchIdByName);
if (spidyApi_searchIdByName_result != null)
{
var Gw2Api_isItemIdinListing_result = api_Handler.GetApi<RootObject>(Gw2Api_allListings + spidyApi_searchIdByName_result.someProperty);
}
当然这会吞下WebException。