我有以下的C#代碼,我已經在我的代碼中重新使用了大約20次。我無法弄清楚如何使它成爲一個子程序,這將允許我重新使用它的B/C類型的對象每次都基於不同的類。如何使用此C#代碼創建子例程?
該代碼的目的是發送一個HTTP請求,收集JSON響應,然後將JSON序列化(使用DataContract)到一個類中以用於其他區域。
這裏就是我的了:這一特定用途
public static ResponseAttachmentIds MakeRequestAttachmentId(string requestUrl, string strToken)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Headers["Authorization"] = "OAuth " + strToken;
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(ResponseAttachmentIds));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
ResponseAttachmentIds jsonResponse = objResponse as ResponseAttachmentIds;
response.Close();
return jsonResponse;
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
return null;
}
}
的DataContract類:
public class ResponseAttachmentIds
{
[DataMember(Name = "done")]
public bool attachmentIds_done;
[DataMember(Name = "records")]
public List<ResponseAttachmentId> attachmentIds_records;
}
[DataContract]
public class ResponseAttachmentId
{
[DataMember(Name = "Id")]
public string attachmentId_strId { get; set; }
[DataMember(Name = "Image_Attachment_Id__c")]
public string attachmentId_strAttachmentId { get; set; }
}
的問題是,我也有這個相同的設置約20個不同的類如ResponseImages
,ResponseProperties
,ResponseProperty
等
任何幫助嗎?
除了託尼和保羅的答案,我建議'DataContractJsonSerializer'是相當有限的。你可能想看看NewtonSoft的Json串行器(你可以在Nuget上找到它) –