3

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

[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 返回一个空值。

有什么建议么?

谢谢。

4

1 回答 1

3

看来我的问题的解决方案是:

        List<AddressContactType> myResults2;

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

我与前面的步骤之一很接近,但这给了我一个完整的列表。

于 2012-11-21T17:26:11.187 回答