我有以下的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上找到它) –