1

I want to deserialize the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<Jobs>
   <Job>
      <Id>1</id>
      <Description>d1</description>
   </Job>
   <Job>
      <Id>2</id>
      <Description>d2</description>
   </Job>
</Jobs>

So I tried to convert the XML to Json and deserialize the jsonstring:

public class Job
{
    public string Id { private get; set; }
    public string ThirdPartyId => $"third-party-id-{Id}";
    public string Description { get; set; }
}

And this how I try to deserialize:

public List<Job> Deserialize(XDocument xDocument)
{
   string jsonString = JsonConvert.SerializeXNode(xDocument);
   return JsonConvert.DeserializeObject<List<Job>>(jsonString);
}

The above fails, I believe because the json contains "xml" node...

{"?xml":{"@version":"1.0","@encoding":"utf-8"},
"Jobs":{"Job":[{"Id":"1","Description":"D1"}, {"Id":"2","Description":"D2"}]}

Is it possible to remove the xml node from xDocument? Is there a better option for doing this?

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137

1 Answers1

0

You can use: XElement

var xmlNoRoot = XElement.Parse(youXML);
var jsonStringNoRoot = JsonConvert.SerializeXNode(xml, Newtonsoft.Json.Formatting.None, true);

ref: https://qawithexperts.com/article/c-sharp/converting-json-to-xml-or-xml-to-json-using-c/347

juazsh
  • 11
  • 3