Error while converting XML response to Json

Goal is to convert XML response to JSON. I am hitting an API endpoint which returns XML data. I recieve the data, convert it to json string but when i try to deserialize the json string, it throws exception that

Additional text encountered after finished reading JSON content: :. Path ”, line 1, position 6

public string GetSaveData(string url)     {         try         {             using (WebClient client = new WebClient())             {                 var response = client.DownloadString(url);                 XmlDocument doc = new XmlDocument();                 doc.LoadXml(response);                 var json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);                 var transactObject1 = JsonConvert.DeserializeObject(json); **//Exception is thrown at this line**             }         }         catch (Exception ex)         {             throw ex;         }          return "success";     }               

Exception is thrown at transactObject1.

Add Comment
1 Answer(s)

So i found the solution by removing the starting tag that declares the XML document which was causing the json string to be malformed.

 public string GetSaveData(string url)     {         try         {             using (WebClient client = new WebClient())             {                 var response = client.DownloadString(url);                 XmlDocument doc = new XmlDocument();                 doc.LoadXml(response);                 foreach (XmlNode node in doc)                 {                     if (node.NodeType == XmlNodeType.XmlDeclaration)                     {                         doc.RemoveChild(node);                     }                 }                 var json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);                 var transactObject1 = JsonConvert.DeserializeObject(json);             }         }         catch (Exception ex)         {             throw ex;         }          return "success";     } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.