Steve
Steve

Reputation: 1551

JsonString Deserialization Error

I am trying to deserialize my JsonString

string JsonString=  "{\"RequestId\":1308,\"Warning\":[\"WARNING_NoOrdersForCustomer\"],\"Customer\":{\"__type\":\"CustomerOrder:#Data\",\"Email\":\"[email protected]\",\"FullName\":\"Anke White\",\"Phone\":\"\",\"Orders\":[]}}"

Here are my 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; }


      }

I tried with this

SalesInfo sales = Deserialize<SalesInfo>(JsonString);

here is the Deserialize

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);
    }
}

But I am getting error message

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.

Please help me resolve this error and deserialize JsonString

Upvotes: 1

Views: 119

Answers (2)

pero
pero

Reputation: 4259

Seems like you are using a proprietary MS Ajax JSON format that inserts these "__type" things that are not compatible with anything else.

So check the serialization part of your solution.

Upvotes: 0

Daniil
Daniil

Reputation: 413

Because your JsonString is incorrect:

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

And there no any information about CustomerOrder type.

The right JsonString in your case is:

{\"RequestId\":1308,\"Warning\":[\"WARNING_NoOrdersForCustomer\"],\"Customer\":{\"Email\":\"[email protected]\",\"FullName\":\"Anke White\",\"Phone\":\"\",\"Orders\":[]}}

enter image description here

Upvotes: 1

Related Questions