[英]Deserializing HttpWebResponse from JSON API in c#
我知道這些主題在stackoverflow上已經存在很多。 但是我有一點不同的問題:
我創建了一個DataContract類,如下所示:
[DataContract]
public class GLSParcelClass {
internal string Location;
internal string ConsignmentId;
internal string Labels;
internal List<Parcels> ParcelList;
internal List<Returns> ReturnList;
}
[DataContract]
public class Parcels {
internal string Location;
internal string TrackId;
internal string ParcelNumber;
}
[DataContract]
public class Returns {
internal string Location;
internal string TrackId;
internal string ParcelNumber;
}
然后,我編寫了以下函數:
WebRequest httpWebRequest = WebRequest.Create(this.GLSUri);
string json = "{" +
"\"shipperId\":\"2764200001 276a165X14\"," +
"\"references\":[\"47110815\"]," +
"\"addresses\":{" +
"\"delivery\":{" +
"\"name1\":\"Max Meyer\"," +
"\"name2\":\"Meyer Ltd.\"," +
"\"street1\":\"Meyer Str. 227\"," +
"\"street2\":\"2. Floor\"," +
"\"country\":\"DE\"," +
"\"zipCode\":\"92753\"," +
"\"city\":\"Passau\"," +
"\"email\":\"maxmeyer@gmail.com\"}}," +
"\"parcels\":[" +
"{" +
"\"weight\":2.5," +
"\"references\":[" +
"\"47110815\"]" +
"}" +
"]" +
"}";
httpWebRequest.ContentType = "application/json";
Type type = httpWebRequest.Headers.GetType();
System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
System.Reflection.MethodInfo m = type.GetMethod("AddWithoutValidate", flags);
m.Invoke(httpWebRequest.Headers, new string[] { "Accept", "application/json" });
m.Invoke(httpWebRequest.Headers, new string[] { "Accept-Language", "de" });
m.Invoke(httpWebRequest.Headers, new string[] { "Accept-Encoding", "gzip,deflate" });
httpWebRequest.Method = "POST";
string lsEncodedCred = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("utf-8").GetBytes("shipmentsapi" + ":" + "shipmentsapi"));
httpWebRequest.Headers.Add("Authorization", "Basic " + lsEncodedCred);
httpWebRequest.PreAuthenticate = true;
StreamWriter streamWriter = null;
using (streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader loStream = new StreamReader(httpResponse.GetResponseStream())) {
GLSParcelClass deserializedParcels = new GLSParcelClass();
string lsJSON = loStream.ReadToEnd();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(lsJSON));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedParcels.GetType());
deserializedParcels = ser.ReadObject(ms) as GLSParcelClass;
ms.Close();
}
我從響應標頭中的JSON API得到了狀態代碼為201的答案“已創建”。 到現在為止還挺好。 但是,當我獲得ResponseStream時,出現錯誤“ System.Runtime.Serialization.SerializationException-反序列化對象時出錯。意外的字符“。”。 。
替代方案我已經使用Mozilla REST客戶端對其進行了測試。 我將獲得具有正確響應流的正確標頭。
響應流還包括base64字符串編碼的pdf文檔。
我真的不知道出什么問題了,希望您能幫助我。
提前很多。
米洛
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.