JsonString反序列化错误

时间:2013-03-24 20:03:15

标签: c# visual-studio-2010 wcf

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

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

以下是我的datacontracts

 [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

2 个答案:

答案 0 :(得分:1)

因为您的JsonString不正确:

\ “客户\”:{的 \ “__类型\”:\ “CustomerOrder:#DATA \”下,\“嗯...

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

你的案例中正确的JsonString是:

{\ “的requestId \”:1308,\ “警告\”:[\ “WARNING_NoOrdersForCustomer \”],的 \ “客户\”:{\ “电子邮件\”:\“xyz@yahoo.com \ “,”FullName \“:\”Anke White \“,\”Phone \“:\”\“,\”Orders \“:[]}}

enter image description here

答案 1 :(得分:0)

好像您使用的是专有的MS Ajax JSON格式,它会插入与其他任何内容不兼容的“__type”内容。

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