5

I am working with C# (ASP.Net, MVC) and Newtonsoft for JSON serialization. I get an XDocument like the one below which I would like to have in JSON format, for the view.

<group>
  <name>Group 1</name>
  <description><p>Description</p></description>
  <section>
    ..
  </section>
  <section>
    ..
  </section>
</group>

I have an Extension like this

private static readonly JsonSerializer jSerializer = JsonSerializer.Create(new JsonSerializerSettings {});

public static string ToJson(this object obj) {
  using (StringWriter writer = new StringWriter()) {
    jSerializer.Serialize(writer, obj);
    return writer.ToString();
  }
}

The problem now is, that the description gets deserialized, so I have something like

... "description": { "p": "Description Text" }

which will be displayed as "[Object object]" when just posted as is.

  • Is there a way to set some JsonProperties for the XDocument (in general), without generating a completely deserialized class?
  • If not, is there a way to set some JsonProperty saying "Keep this as string, do not serialize any further"
  • If I were to use an XSD generated class for this, what "type" would I need to set? "anyType"?

Help would be appreciated, Best regards.

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
Cabadath
  • 897
  • 3
  • 13
  • 23

2 Answers2

12

I am adding this answer due to it's google search rank when looking up "c# convert xml to json XDocument".

string json = JsonConvert.SerializeXNode(xDocument);

This answer uses the more modern XNode vs XmlNode

Troy Witthoeft
  • 2,498
  • 2
  • 28
  • 37
4

Using Json.NET you can serialize an XML node directly to JSON using the following line:

string json = JsonConvert.SerializeXmlNode(xmlNode);

To convert your XDocument to XmlDocument see this question:

Converting XDocument to XmlDocument and vice versa

You can then use your converted XmlDocument as parameter for SerializeXmlNode() because it inherits from XmlNode.

Community
  • 1
  • 1
fero
  • 6,050
  • 1
  • 33
  • 56
  • I would like to not use the JsonConvert, because it does not use the same serializer settings. It's not really an issue, I know how to convert Json to XmlDocument. But you are basically answering my question in going over XML to object and not directly. Last thing I would need to know is which type I'd have to set in the XSD file. – Cabadath Aug 10 '12 at 12:46
  • 3
    Perhaps a stupid question, but why are you not using `SerializeXNode` instead of `SerializeXmlNode` – JP Hellemons Oct 28 '14 at 09:40
  • 1
    @JPHellemons I have no clue. Maybe the method hasn't existed yet when I wrote the answer. But I honestly don't know anymore. – fero Oct 28 '14 at 12:33