简体   繁体   中英

Change the namespace of DataContract

I have to retreive xml data from database saved by other Windows service.

Here the XML data stored in my database :

<ArrayOfDescription.Traduction xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/OtherNamespace">
   <Description.Traduction>
      <Description>Contact ouvert</Description>
      <Label>Ouvert</Label>
      <LcId>12</LcId>
   </Description.Traduction>
   <Description.Traduction>
      <Description>Contact open</Description>
      <Label>Open</Label>
      <LcId>9</LcId>
   </Description.Traduction>
</ArrayOfDescription.Traduction>

My class name is Description and my string property name is TradBlob. No problem to retreive the data stored in my database. Then I have defined a partial class of Description to help me with deserialization.

public partial class Description
{
     [DataContract(Name = "Description.Traduction", Namespace = "http://schemas.datacontract.org/2004/07/OtherNamespace")]
     public class Traduction
     {
        public string Description { get; set; }
        public string Label { get; set; }
        public int LcId { get; set; }
     }
}

Then in the UI side, I can write :

LabelTrad = SerializerHelper.Deserialize<List<Description.Traduction>>(TradBlob).Single(x=>x.LcId == CurrentLcId).Label

Here my deserialization method :

public static T Deserialize<T>(string xml)
{
  if (string.IsNullOrEmpty(xml)) return default(T);

  try
  {
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
      var serializer = new DataContractSerializer(typeof(T));
      T theObject = (T)serializer.ReadObject(stream);
      return theObject;
    }
  }
  catch (SerializationException e)
  {
    // La déserialisation s'est mal passée, on retourne null
    return default(T);
  }
}

My issue is that the deserialization doesn't work as expeced. Label is null.

Do you have any idea of what goes wrong ?

Note: I can't modify the creation of Traduction class inside Description class.

I forgot to add DataMember annotation to Description, Label and LcId properties. Thank you everyone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM