WCF service returns XML or JSON-formatted data

Source: Internet
Author: User
Tags string format

The first way
public string GetData (string format)
{
string res = null;
Student stu = new Student
{
Stuid = 3,
Stuname = "John Doe"
};
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;
}
The second way
Public Message GetData (string format)
{
Weboperationcontext context = weboperationcontext.current;
Student stu = new Student
{
Stuid = 222,
Stuname = "Zhang San"
};
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;}
}

WCF service returns XML or JSON-formatted data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.