1

I have an object that contains a string property, which returns a string that contains HTML tags:

[DataMember]
public string SomeProperty
{
    return "<HTMLTag>";
}

When this object is serialized by DataContractJsonSerializer.WriteObject(), the '<' and '>' characters are converted to "&lt;" and "&gt;". Is there any attribute (or something else) that can prevent this from happening? I know WriteRaw will do the trick, but I can't change the DataContractJsonSerializer.WriteObject() is beyond my control. Thanks.

Kurubaran
  • 8,696
  • 5
  • 43
  • 65
John W
  • 610
  • 8
  • 20
  • 3
    Writing `` into your serialized XML would make the XML invalid, because of missing closing tag. – MarcinJuraszek Dec 27 '13 at 19:20
  • 2
    It might sound funny, but *DataContractJsonSerializer* is indeed being derived from *XmlObjectSerializer*, which explains the observed behavior. Perhaps using Json.NET could be an alternative, if JSON (de)serialization is all you are looking for. –  Dec 27 '13 at 19:22
  • The returned string is just an example. I only care about the character conversion. – John W Dec 27 '13 at 19:24
  • Similar question http://stackoverflow.com/questions/1506499/xml-serialization-of-html – Amitd Dec 27 '13 at 19:26
  • I have to use DataContractJsonSerializer.WriteObject(). I can't change it to anything else. It's beyond my control. – John W Dec 27 '13 at 19:26
  • Can you explain your actual problem? Why is the default encoding a problem? The reading party should follow the same encoding rules as the writer, if you add exceptions (i.e. don't escape characters that should be escaped), you're breaking convention and probably other software. – CodeCaster Dec 27 '13 at 19:29

2 Answers2

0

There is a similar problem considered. Mentioning this, you can encode your HTML into different data, transfer and then decode.

Community
  • 1
  • 1
Ilya Tereschuk
  • 1,204
  • 1
  • 9
  • 21
0

By using

string noEncoding = new XElement("foo", new XCData("a < b")).ToString();

This will produce

<foo><![CDATA[a < b]]></foo>
Sebastien F.
  • 1,613
  • 2
  • 23
  • 40
Rakesh Raut
  • 183
  • 3
  • 12