Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument to JSON, JsonProperties

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.

like image 805
Cabadath Avatar asked Dec 27 '22 20:12

Cabadath


1 Answers

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

like image 200
Troy Witthoeft Avatar answered Jan 11 '23 21:01

Troy Witthoeft