1

I am trying to Serialize a class in C# this works fine when there is no null value in the object. Following is the class

public class EnquiryResponseInfo
{
    public string EnquiryId { get; set; }
    public EnquiryViewModel Enquiry { get; set; }
}

When I supply the following value it works great.

EnquiryResponseInfo tt = new EnquiryResponseInfo()
{
    EnquiryId = "xxx",
    Enquiry = new EnquiryViewModel()
    {
        Name = "Test user",
        Address = "Test Address"
    }
}

But when Enquiry is null it does not Serialize. I have a condition where the Enquiry will be null but there will be value in the EnquiryId there.

Following is the method to Serialize the class.

public static string Serialize<T>(T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

Please help.

Rober
  • 73
  • 1
  • 8
  • "But when Enquiry is null it does not Serialize." - Enquiry does not serialize? or the entire type does not serialize? it should work fine if the property is null - what exactly happens? example showing it working fine, with output: https://gist.github.com/mgravell/bd817bebd0f4a3d52c5edf0bb4f0fcf8 – Marc Gravell Nov 25 '19 at 11:52
  • List ApplicationInfo = new List() { new EnquiryResponseInfo() { EnquiryId = "e30a092d-b7c1-4516-8e48-50efe307c7e5", Enquiry = null } }; – Rober Nov 25 '19 at 11:57
  • There was an error reflecting type 'System.Collections.Generic.List`1[EnquiryResponseInfo]'. Gives me this error... – Rober Nov 25 '19 at 11:58
  • "There was an error reflecting type 'System.Collections.Generic.List\`1[EnquiryResponseInfo]'" - tip: look at `.InnerException` - and `.InnerException.InnerException` etc (as far down as it goes); `XmlSerializer` is actually *really good* at telling you what went wrong, but it is often a few levels down the exception stack – Marc Gravell Nov 25 '19 at 11:59
  • here's an updated gist that uses your `Serialize` method, and uses a `List` to match the post/comments: https://gist.github.com/mgravell/503a885c291a4eeee2be201473059f75 - it *works fine* - so: whatever the problem is, it *isn't in the question*; you need to either post enough code for us to repro the problem, or look at the nested exceptions – Marc Gravell Nov 25 '19 at 12:05
  • Dictionary dd = new Dictionary(); this is not being serialized buddy... – Rober Nov 25 '19 at 12:21
  • literally nothing in the question uses `Dictionary` - can you show this in full context? – Marc Gravell Nov 25 '19 at 13:27
  • see also: https://stackoverflow.com/questions/2911514/why-doesnt-xmlserializer-support-dictionary – Marc Gravell Nov 25 '19 at 13:29

3 Answers3

2

Try to decorate the property Enquiry with [XmlElement(IsNullable = true)]

Quoted from here

Shrembo
  • 833
  • 1
  • 8
  • 27
  • I figure out that now, I think the usage of this value is to prevent the serializer from serializing the value if its null, is it right? @MarcGravell – Shrembo Nov 25 '19 at 12:08
  • no, not really; it already does that - this just causes it to be serialized *in a specific way* when null, i.e. expressed in xml as a nil – Marc Gravell Nov 25 '19 at 12:15
0

The code as shown in the question and comments is perfectly fine; XmlSerializer has reasonable default behaviors with null, so: that isn't the problem.

Whatever is happening : it isn't shown in the question. Most likely, there are other properties on EnquiryViewModel that are not friendly for XmlSerializer - perhaps they are non-public types, or have no public parameterless constructor. The way to find out is to look at the nested exceptions - for example, in Serialize<T>:

try
{
    // ... what you had before
}
catch (Exception ex)
{
    while (ex != null)
    {
        Debug.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
    throw;
}

This should tell you what exactly it finds objectionable about the model, in the debug output (or just put a break-point on the Debug.WriteLine line, and read all of the messages in the debugger).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
-1

keep your property as nullable which would solve the problem. Example code u can refer below.

 [XmlRoot("test")]  
    public class Test {  
        int? propertyInt;  
        string propertyString;  

        [XmlAttribute("property-int")]  
        public int PropertyInt {  
            get { return (int)propertyInt; }  
            set { propertyInt = (int)value; }  
        }  

        public bool PropertyIntSpecified {  
            get { return propertyInt != null; }  
        }  

        [XmlAttribute("property-string")]  
        public string PropertyString {  
            get { return propertyString; }  
            set { propertyString = value; }  
        }  
    }  

    class Program {  
        static void Main(string[] args) {  

            XmlSerializer serializer = new XmlSerializer(typeof(Test));  
            serializer.Serialize(Console.Out, new Test() { PropertyInt = 3 });  //only int will be serialized  
            serializer.Serialize(Console.Out, new Test() { PropertyString = "abc" }); // only string will be serialized  
            serializer.Serialize(Console.Out, new Test() { PropertyInt = 3, PropertyString = "abc" }); // both - int and string will be serialized  


        }  
    }