我想了解如何使用JSON响应继续创建基于REST的WCF服务和实体数据模型。我已按照以下列出的说明进行操作:
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
这是IService1.cs文件中的命名空间DeviceManagementService_Rest
:
下面。 deviceOS是用于列出运行特定操作系统的不同设备的参数。
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, UriTemplate = "json/{deviceOS}", BodyStyle = WebMessageBodyStyle.Bare)]
string JSONData(string deviceOS);
}
创建此类以查询数据并转换为JSON格式:
public class Service1 : IService1
{
DeviceManEntities dme;
public string JSONData(string deviceOS)
{
dme = new DeviceManEntities();
var result = (from m in dme.DeviceInfoes
select new
{
Name = m.deviceName,
OS = m.deviceOS,
UID = m.deviceUID
}).ToList();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(result);
}
}
问题是:我收到了以下格式的回复:
"[{\"Name\":\"Galaxy S3\",\"OS\":\"Andriod\",\"UID\":\"101\"},
{\"Name\":\"iPhone 5-D1\",\"OS\":\"iOS\",\"UID\":\"123\"}]"
理想情况下,我希望它是这样的:
"[{"Name":"Galaxy S3","OS":"Android","UID":"101"}
{"Name":"iPhone 5-D1","OS":"iOS","UID":"123"}]"
答案 0 :(得分:2)
您不需要自己将响应序列化为Json。将其保留给WCF,这将通过设置[WebInboke]
ResponseFormat = WebMessageFormat.Json
属性。
只需定义服务契约,使其返回.net对象,WCF将为您处理序列化。按照您的示例,为设备创建一个类,并在服务操作中返回一个列表(如果您愿意,则返回一个数组):
public class Device
{
public string Name { get; set; }
public string OS { get; set; }
public int UID { get; set; }
}
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "json/{deviceOS}",
BodyStyle = WebMessageBodyStyle.Bare)]
List<Device> JSONData(string deviceOS);
}
public class Service1 : IService1
{
DeviceManEntities dme;
public List<Device> JSONData(string deviceOS)
{
dme = new DeviceManEntities();
return (from m in dme.DeviceInfoes
select new Device
{
Name = m.deviceName,
OS = m.deviceOS,
UID = m.deviceUID
}).ToList();
}
}