2013-03-24 137 views
1

我想反序列化我JsonStringJsonString反序列化錯誤

string JsonString= "{\"RequestId\":1308,\"Warning\":[\"WARNING_NoOrdersForCustomer\"],\"Customer\":{\"__type\":\"CustomerOrder:#Data\",\"Email\":\"[email protected]\",\"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

+0

您是否考慮過使用'System.Web.Script.Serialization.JavaScriptSerializer'來代替?使用IMO更容易。這同樣適用於Json.NET庫:http://json.codeplex.com/ – Simeon 2013-03-24 20:10:29

+0

如果您想在線免費提供'JSON驗證'http://jsonlint.com/ – MethodMan 2013-03-24 20:42:56

回答

1

因爲你JsonString是不正確的:

\ 「客戶\」:{\「__類型\「:\」CustomerOrder:#Data \「,\」Em ...

並且沒有關於CustomerOrder類型的任何信息。

在你的情況下,右側JsonString是:

{\ 「請求ID \」:1308,\ 「警告\」:\ 「WARNING_NoOrdersForCustomer \」],\ 「客戶\」:{\「電子郵件\「:\」[email protected] \「,\」FullName \「:\」Anke White \「,\」Phone \「:\」\「,\」Orders \「:[]}}

enter image description here

0

好像你正在使用專有的MS Ajax JSON格式,插入這些與其他任何東西不兼容的「__type」東西。

因此請檢查解決方案的序列化部分。