为什么我的json反序列化失败了?

时间:2012-11-21 16:17:31

标签: c# json deserialization restsharp rest-client

我有以下两个对象(我无法控制且无法更改):

[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),但它们都是null,并且只显示了每个的一个实例。

尝试3只返回result2的空值。

有什么建议吗?

感谢。

1 个答案:

答案 0 :(得分:3)

我的问题的解决方案似乎是:

        List<AddressContactType> myResults2;

        using (Stream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(myResults)))
        {
            myResults2 = JsonConvert.DeserializeObject<List<AddressContactType>>(new StreamReader(ms2).ReadToEnd());
        }

我接近前面的一个步骤,但这给了我一个完整的清单。

相关问题