Cannot deserialize xml string with Newtonsoft.Json.JsonConvert.DeserializeObject

…衆ロ難τιáo~ 提交于 2019-12-04 16:48:48

You are getting an error because JsonConvert.DeserializeObject() expects JSON input, not XML. If you want to handle XML with a JObject, you'll need to convert the XML to JSON first. The JsonConvert class has a SerializeXmlNode() method for this purpose.

Demo:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        <AbcDto xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Abc"">
          <Id>2</Id>
          <Description>sample string 4</Description>
          <Name>sample string 3</Name>
          <PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
          <Status>Active</Status>
          <TimeZoneId>USCentral</TimeZoneId>
        </AbcDto>";

        // If the json string contains XML, convert it to JSON
        if (json.TrimStart().StartsWith("<"))
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(json);
            json = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
        }

        // Now you can load the JSON into a JObject
        var jsonObject = JObject.Parse(json);
        var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
        foreach (string name in jsonPropertyNames)
        {
            Console.WriteLine(name);
        }
    }
}

Output:

@xmlns:i
@xmlns
Id
Description
Name
PolicyId
Status
TimeZoneId
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!