码迷,mamicode.com
首页 > Web开发 > 详细

WCF服务返回XML或JSON格式数据

时间:2017-04-29 23:30:51      阅读:353      评论:0      收藏:0      [点我收藏+]

标签:gets   using   memory   createjs   tty   string   orm   stream   json   

第一种方式
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; }
}

WCF服务返回XML或JSON格式数据

标签:gets   using   memory   createjs   tty   string   orm   stream   json   

原文地址:http://www.cnblogs.com/sjqq/p/6786442.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!