-1

How can I convert this Class into XML ? Or is there any possible way I can convert a JSON String for the same class directly into XML ? I am not getting an idea or a sample code to start with the conversion.

public class Contacts
        {
            public Datum[] data { get; set; }
            public Info info { get; set; }
        }
public class Datum
        {
            public Owner Owner { get; set; }
            public object Email { get; set; }
            public string Description { get; set; }
            public string currency_symbol { get; set; }
            public string Mailing_Zip { get; set; }
}
 public class Owner
        {
            public string name { get; set; }
            public string id { get; set; }
        }

public class Info
        {
            public int per_page { get; set; }
            public int count { get; set; }
            public int page { get; set; }
            public bool more_records { get; set; }
        }

Please help in converting the Class to XML or the JSON String based on the above class into an XML directly.

The scenario is that, I am receiving a JSON result from the API and this result needs to be processed in the SQL Server where the datatype has been kept as XML. I am hoping that this can be achieved successfully.

Dilip Nair
  • 61
  • 1
  • 7

2 Answers2

0

There are plenty of online resources to convert c# properties in to JSON or XML without any effort , try this and this and JSON to XML converter this too

Update If you wish to convert inside the code try below. p.s (use Json.NET)

string json = //set your result JSON from the web API call;

XNode node = JsonConvert.DeserializeXNode(json, "Root");

Console.WriteLine(node.ToString());

this will convert your Json to XML

PrathapG
  • 751
  • 1
  • 7
  • 21
0

I solved the same converting the JSON to Class object and serializing the XML from the Class object.

public static string GetXMLFromObject(object o)
        {
            StringWriter sw = new StringWriter();
            XmlTextWriter tw = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(o.GetType());
                tw = new XmlTextWriter(sw);
                serializer.Serialize(tw, o);
            }
            catch (Exception ex)
            {
                //Handle Exception Code
            }
            finally
            {
                sw.Close();
                if (tw != null)
                {
                    tw.Close();
                }
            }
            return sw.ToString();
        }
Dilip Nair
  • 61
  • 1
  • 7