1

我正在尝试反序列化我的 JsonString

string JsonString=  "{\"RequestId\":1308,\"Warning\":[\"WARNING_NoOrdersForCustomer\"],\"Customer\":{\"__type\":\"CustomerOrder:#Data\",\"Email\":\"xyz@yahoo.com\",\"FullName\":\"Anke White\",\"Phone\":\"\",\"Orders\":[]}}"

这是我的数据合同

 [DataContract]
      public class SalesInfo
      {
          [DataMember(Name = "RequestId")]
          public string RequestId { get; set; }

          [DataMember(Name = "Warning")]
          public string[] Warning { get; set; }

          [DataMember(Name = "Customer")]
          public Customer CustomerData { get; set; }

      }

[DataContract]
    public class Customer
      {
          [DataMember(Name = "Email")]
          public string Email { get; set; }

          [DataMember(Name = "FullName")]
          public string FullName { get; set; }

          [DataMember(Name = "Phone")]
          public string Phone { get; set; }

          [DataMember(Name = "Orders")]
          public string[] Orders { get; set; }


      }

我试过这个

SalesInfo sales = Deserialize<SalesInfo>(JsonString);

这是反序列化

private static T Deserialize<T>(string json)
{
    var instance = Activator.CreateInstance<T>();
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serializer = new DataContractJsonSerializer(instance.GetType());
        return (T)serializer.ReadObject(ms);
    }
}

但我收到错误消息

Element ':Customer' contains data from a type that maps to the name 'http://schemas.datacontract.org/2004/07/Data:CustomerOrder'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'CustomerOrder' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.

请帮我解决这个错误并反序列化 JsonString

4

2 回答 2

1

因为您的 JsonString 不正确:

\"Customer\":{ \"__type\":\"CustomerOrder:#Data\" ,\"Em...

并且没有关于 CustomerOrder 类型的任何信息。

在您的情况下,正确的 JsonString 是:

{\"RequestId\":1308,\"Warning\":[\"WARNING_NoOrdersForCustomer\"], \"Customer\":{\"Email\":\"xyz@yahoo.com\",\"FullName\ ":\"安克白\",\"电话\":\"\",\"订单\":[]}}

在此处输入图像描述

于 2013-03-24T20:39:18.877 回答
0

似乎您使用的是专有的 MS Ajax JSON 格式,该格式插入了这些与其他任何东西都不兼容的“__type”东西。

因此,请检查解决方案的序列化部分。

于 2013-03-24T21:17:26.270 回答