0

I would like to create a custom serializable "string" class to handle the default string formatting without implement the logic in all of the modells.

I created a serializable class with implicit string operator

[Serializable]
public class FormattedString : ISerializable
{

    public static implicit operator FormattedString(string s)
    {
        return new FormattedString() { OriginalString = s };
    }

    public string OriginalString { get; set; }

    public override string ToString()
    {
        if (string.IsNullOrWhiteSpace(this.OriginalString))
            this.OriginalString = String.Empty;

        this.OriginalString = OriginalString.Trim().Replace(Environment.NewLine, " ");
        return this.OriginalString;
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("string", this.ToString());
    }
}

My problem is the serialized object look like this

<?xml version="1.0" encoding="UTF-8"?>
<SomeXml>
  <Zip2>
    <OriginalString>2094</OriginalString>
  </Zip2>
</SomeXml>

instead of this

<?xml version="1.0" encoding="UTF-8"?>
<SomeXml>
  <Zip2>2094</Zip2>
</SomeXml>

How can I serialize an object the way i want? Is this possible at all?

Smiley
  • 58
  • 5
  • The example XML is wrong if I use the "info.AddValue("string", this.ToString());" method. In this case the tag will be "2094" – Smiley Aug 01 '18 at 13:12
  • 1) What serializer are you using? [tag:xmlserializer] does not support `ISerializable`. [tag:datacontractserializer] does. 2) Can you please [edit] your question to provide a [mcve] that shows how you are generating that XML? – dbc Aug 01 '18 at 18:51

0 Answers0