Search This Blog

Monday, August 15, 2011

Convert XElements to Json

You need to capture the data type in a class that is serializable.
In this example I use Employee to do so. The first action will be to construct an IEnumerable of Employee:


XElement empXml = GetEmployees();
 var empJson = from emp in empXml.Descendants("Employee")
               select new Employee
               {
                      ID = emp.Element("ID").Value,
                      FirstName = emp.Element("FirstName").Value,
                      Department = emp.Element("Department").Value,
                      City = emp.Element("City").Value
               };

The second step is to serialize the enumeration into the memory stream.
var ser = new  DataContractJsonSerializer(typeof(IEnumerable));
  var ms = new MemoryStream();
  ser.WriteObject(ms, empJson);
And at last, we can take the generated stream as a string just before closing the stream.

string json = Encoding.Default.GetString(ms.ToArray());
ms.Close();

No comments: