我有一个方法,我用来处理Json响应。由于这是线束的一部分,我将创建许多不同的数据对象,因此可以使它更通用,因此我不必为我创建的每个不同的数据对象创建相同的代码。
[DataContract]
class Stats
{
[DataMember]
public string StatusCode {get;set;}
[DataMember]
public int ProspectCount {get;set;}
[DataMember]
public int MessageCount {get;set;}
[DataMember]
public int NewListingCount {get;set;}
[DataMember]
public int ReminderCount {get;set;}
[DataMember]
public int MyListingCount {get;set;}
[DataMember]
public int OfficListingCount {get;set;}
}
public static Stats SendRequest(string requestUrl)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Stats));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
Stats jsonResponse
= objResponse as Stats;
return jsonResponse;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
我基本上希望能够创建第二个和第三个数据合同,而无需重新创建SendRequest方法。
答案 0 :(得分:0)
两个选项:
1:使SendRequest方法成为另一个类中唯一的静态方法,让每个需要它的对象都像这样调用它:
RequestSender.SendRequest(requestUrl).
2:使这个和你必须编写的其他类扩展一个包含SendRequest(String requestUrl)方法的超类,以便他们可以通过继承访问同一个方法。
答案 1 :(得分:0)
通用方法是否有效?签名可能如下所示:
public static T SendRequest<T>(string requestUrl) where T : class
在方法正文中,您将Stats
替换为T
。
用法:
Stats response = RequestSender.SendRequest<Stats>("some URL");
OtherClass anotherResponse = RequestSender.SendRequest<OtherClass>("some other URL");
答案 2 :(得分:0)
我最终将Json.NET用于序列化部分。这将完成我需要的一切。所以现在我的方法看起来像:
public static string ProcessRequest(string requestUrl)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
string responseContents;
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
Stream responseStream = response.GetResponseStream();
using(StreamReader readStream = new StreamReader(responseStream))
{
responseContents = readStream.ReadToEnd();
}
return responseContents;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
另一种方法中的序列化组件是一个简单的一行,它将响应作为字符串。:
Stats results = JsonConvert.DeserializeObject<Stats>(response);