第一种方式
public string GetData( string format)
{
string res = null;
Student stu = new Student
{
StuID = 3,
StuName ="李四"
};
using (MemoryStream ms = new MemoryStream())
{
XmlObjectSerializer sz = null;
if ( format.ToLower() == "xml")
{
sz = new DataContractSerializer(stu.GetType());
}
else
{
sz = new DataContractJsonSerializer(stu.GetType());

}
sz.WriteObject(ms, stu);
res = Encoding.UTF8.GetString(ms.ToArray());
}
return res;
}
第二种方式
public Message GetData(string format)
{
WebOperationContext context = WebOperationContext.Current;
Student stu = new Student
{
StuID = 222,
StuName = "张三"
};
Message msgreturn = null;
if (format.ToLower() == "xml")
{
msgreturn = context.CreateXmlResponse<Student>(stu);
}
else
{
msgreturn = context.CreateJsonResponse<Student>(stu);
}

return msgreturn;
}

[DataContract]
public class Student
{
[DataMember(Name="ID")]
public int StuID { get; set; }

[DataMember(Name = "stu_name")]
public string StuName { get; set; }
}