3
我有以下兩個對象(我不控制,並不能改變):爲什麼我的json反序列化失敗?
[Serializable]
[DataContract]
public class AddressContactType : BaseModel
{
public AddressContactType();
[DataMember]
public string AddressContactTypeName { get; set; }
}
[Serializable]
[DataContract]
public abstract class BaseModel
{
protected BaseModel();
[DataMember]
public int Id { get; set; }
[DataMember]
public string NativePMSID { get; set; }
[DataMember]
public string PMCID { get; set; }
}
我使用RESTClient實現做一個GET調用來檢索JSON此數據。請求成功。返回的JSON是:
[{"Id":0,"NativePMSID":"1","PMCID":"1020","AddressContactTypeName":"Home"},{"Id":0,"NativePMSID":"2","PMCID":"1020","AddressContactTypeName":"Apartment"},{"Id":0,"NativePMSID":"3","PMCID":"1020","AddressContactTypeName":"Vacation"},{"Id":0,"NativePMSID":"3","PMCID":"1020","AddressContactTypeName":"Other"}]
從這一點來說我試圖反序列化三種不同方式的數據。
我的代碼:
var request = new RestRequest("AddressContactType", Method.GET);
request.AddHeader("Accept", "application/json");
request.AddParameter("PMCID", "1020");
#region JSON Deserialization
// ---- Attempt #1
var response = client.Execute<AddressContactType>(request);
// ---- Attempt #2
var myResults = response.Content;
var ms = new MemoryStream(Encoding.UTF8.GetBytes(myResults));
var ser = new DataContractJsonSerializer(typeof(AddressContactType));
var result = (AddressContactType)ser.ReadObject(ms);
// ---- Attempt #3
var jsonSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var result2 = new AddressContactType();
result2 = JsonConvert.DeserializeObject<AddressContactType>(new StreamReader(ms).ReadToEnd(), jsonSettings);
#endregion
在試圖1,RESTClient實現嘗試返回錯誤:「無法投類型 'RestSharp.JsonArray' 爲類型「System.Collections.Generic.IDictionary`2 [對象System.String,System.Object的]」「。
在嘗試2下,對象結果顯示爲具有正確的屬性(Id,NativePMSID,PMCID和AddressContactTypeName),但它們全都爲空,並且僅顯示每個實例的一個實例。
嘗試3只是爲result2返回空值。
有什麼建議嗎?
謝謝。
謝謝!你能解釋它爲什麼有效嗎? – OriBr