Monday, September 25, 2023

Convert Json to XML C#

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;

namespace JSONStringConvert
{
    public class Utilities
    {
        public static string ConvertToXML(string json)
        {
            //if an empty string is passed, return empty string without conversion
            if (string.IsNullOrEmpty(json))
                return string.Empty;
            //if invalid json is passed, throw error.
            ValidateJSON(json);
            //Convert Json to XML
            XDocument xmlDoc = JsonConvert.DeserializeXNode(json);
            return xmlDoc.ToString();
        }
        public static void ValidateJSON(string json)
        {
            try
            {
                var jsonObject = JObject.Parse(json);
            }
            catch (Exception ex)
            {
                throw new InvalidCastException("Provided json is not valid.", ex);
            }
        }
    }
}

No comments:

Post a Comment

Table browser URL in D365FO

Critical Thinking icon icon by Icons8