【问题标题】:Why is my json deserialization failing?为什么我的 json 反序列化失败了?
【发布时间】:2012-11-21 16:17:30
【问题描述】:

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

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

有什么建议吗?

谢谢。

【问题讨论】:

    标签: c# json deserialization restsharp rest-client


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多