I have written a simple webAPI program which returns JSON by default when running , I want the values in XML format so I tried below code it always returns string for me, have also tried multiple solution from this stackoverflow post but all returns string.
Model class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JsonToXML2.Models
{
public class Employee
{
public int EmployeeId
{
get;
set;
}
public string EmployeeName
{
get;
set;
}
public string Address
{
get;
set;
}
public string Department
{
get;
set;
}
}
}
Controller Class :
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;
namespace JsonToXML2.Controllers
{
public class EmployeeController : ApiController
{
IList<Employee> employees = new List<Employee>()
{
new Employee()
{
EmployeeId = 1, EmployeeName = "Mukesh Kumar", Address = "New Delhi", Department = "IT"
},
new Employee()
{
EmployeeId = 2, EmployeeName = "Banky Chamber", Address = "London", Department = "HR"
},
new Employee()
{
EmployeeId = 3, EmployeeName = "Rahul Rathor", Address = "Laxmi Nagar", Department = "IT"
},
new Employee()
{
EmployeeId = 4, EmployeeName = "YaduVeer Singh", Address = "Goa", Department = "Sales"
},
new Employee()
{
EmployeeId = 5, EmployeeName = "Manish Sharma", Address = "New Delhi", Department = "HR"
},
};
public IList<Employee> GetAllEmployees()
{
//Return list of all employees
return employees;
}
public String GetEmployeeDetails(int id)
{
//Return a single employee detail
var employee = employees.FirstOrDefault(e => e.EmployeeId == id);
if (employee == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return (GenerateXmlResponse(employee));
}
// override StringWriter
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
private string GenerateXmlResponse(Object obj)
{
Type t = obj.GetType();
var xml = "";
using (StringWriter sww = new Utf8StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
var ns = new XmlSerializerNamespaces();
// add empty namespace
ns.Add("", "");
XmlSerializer xsSubmit = new XmlSerializer(t);
xsSubmit.Serialize(writer, obj, ns);
xml = sww.ToString(); // Your XML
}
}
return xml;
}
}
}
To access the app I am simply hitting the URL as https://localhost:44379/api/employee/1 in postman, the problem is data is in String format within double quotes, How can I get the data in pure XML format?