DataContractJsonSerializer (位于 System.Runtime.Serialization.Json)
JsonObject (位于System.Json,将JSON数据流转换成为可读写的对象)
JsonArray (位于System.Json, 对JSON数据流转换成为JsonObject数组形式,可支持LINQ查询)
注:如果要引用System.Runtime.Serialization.Json名空间里的Json,则必须也引用System.ServiceModel,否则Json会无法使用。
这三类以都支持Stream类型参数,而该参数就是从WCF获取的JSON数据流。使用它们也很简单,首先我们需
要建立一个AJAX型WCF,如下图:
因为我们是获取用户数据,所以将这个WCF命名为UserService.cs:
然后对这个WCF做如下修改:
1.对SVC头文件添加WebServiceHostFactory,如下:
<%@ ServiceHost Language="C#" Debug="true" Service="UserService"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
2.注释web.config中的enableWebScript节点,如下:
<behavior name="UserServiceAspNetAjaxBehavior">
<!--<enableWebScript />-->
</behavior>
<!--<enableWebScript />-->
</behavior>
当然这里所用的WCF为,主要是为了支持形如下面的请求链接方式:
[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUser[/url]
而下面就是WCF中的代码段:
[DataContract]
public class UserInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public bool IsMember { get; set; }
}
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class UserService
{
List<UserInfo> userList = new List<UserInfo>
{
new UserInfo {Name = "赵二", Address = "北京", Age = 2, IsMember = true},
new UserInfo {Name = "张三", Address = "北京", Age = 3, IsMember = false},
new UserInfo {Name = "李四", Address = "北京", Age = 4, IsMember = true},
new UserInfo {Name = "王五", Address = "北京", Age = 5, IsMember = false},
};
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUser")]
public UserInfo GetUser()
{
return new UserInfo() { Name = "张三", Address = "北京", Age = 3, IsMember = true };
}
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUserListByAge/{age}")]
public UserInfo GetUserListByAge(string age)
{
return (from u in userList
where u.Age == int.Parse(age)
select new UserInfo
{
Age = u.Age,
Name = u.Name,
IsMember = u.IsMember,
Address = u.Address
}).SingleOrDefault();
}
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUserList")]
public List<UserInfo> GetUserList()
{
return userList;
}
}
public class UserInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public bool IsMember { get; set; }
}
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class UserService
{
List<UserInfo> userList = new List<UserInfo>
{
new UserInfo {Name = "赵二", Address = "北京", Age = 2, IsMember = true},
new UserInfo {Name = "张三", Address = "北京", Age = 3, IsMember = false},
new UserInfo {Name = "李四", Address = "北京", Age = 4, IsMember = true},
new UserInfo {Name = "王五", Address = "北京", Age = 5, IsMember = false},
};
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUser")]
public UserInfo GetUser()
{
return new UserInfo() { Name = "张三", Address = "北京", Age = 3, IsMember = true };
}
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUserListByAge/{age}")]
public UserInfo GetUserListByAge(string age)
{
return (from u in userList
where u.Age == int.Parse(age)
select new UserInfo
{
Age = u.Age,
Name = u.Name,
IsMember = u.IsMember,
Address = u.Address
}).SingleOrDefault();
}
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUserList")]
public List<UserInfo> GetUserList()
{
return userList;
}
}
上面代码中的方法:
GetUser() //对应DataContractJsonSerializer的调用演示
GetUserList(string age) //对应JsonObject的调用演示
GetAllUser() //对应JsonArray的调用演示
分别使用了WebGet属性(位于System.ServiceModel.Web),且ResponseFormat皆为WebMessageFormat.Json
(当然也支持WebMessageFormat.Xml)。而UriTemplate属性为该服务所支持的浏览器链接地址。
当对上面的WCF编译运行之后,我们在浏览器中输入下面地址:
[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUser[/url] //参见UriTemplate设置
则此时IE会弹出一个保存窗口,如下截图:
而保存到本地的文件内容如下:
{"Address":"北京","Age":12,"IsMember":true,"Name":"张三"}
看来通过对上述链接的调用,WCF会直接将我们想要的用户信息转换成JSON格式。
注:另个两个链接及其返回JSON内容分别如下所示
[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUserListByAge/2[/url]
{"Address":"北京","Age":2,"IsMember":true,"Name":"赵二"}
[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUserList[/url]
[{"Address":"北京","Age":2,"IsMember":false,"Name":"赵二"},
{"Address":"北京","Age":3,"IsMember":false,"Name":"张三"},
{"Address":"北京","Age":4,"IsMember":false,"Name":"李四"},
{"Address":"北京","Age":5,"IsMember":false,"Name":"王五"}]//自动转成JSON数组
{"Address":"北京","Age":3,"IsMember":false,"Name":"张三"},
{"Address":"北京","Age":4,"IsMember":false,"Name":"李四"},
{"Address":"北京","Age":5,"IsMember":false,"Name":"王五"}]//自动转成JSON数组
下面我们就来看一下Silverlight是何使用来解析上面传回来的JSON数据的.
首先看一下使用DataContractJsonSerializer的示例(详见注释):
private void GetUserToDataContract_Click(object sender, RoutedEventArgs e)
{
Uri serviceUri = new Uri("[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUser[/url]");
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(serviceUri);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
//声明一个UserInfo类型的DataContractJsonSerializer实例
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserInfo));
//获取JSON数据流的信息,并将它转换成为UserInfo实例
UserInfo userInfo = (UserInfo)serializer.ReadObject(e.Result);//e.Result为JSON流数据
//下面显示userInfo中的数据信息
UserList.Items.Add(string.Format("Name:{0}, Address:{1}, Age:{2}, IsMember:{3} ",
userInfo.Name,
userInfo.Address,
userInfo.Age,
userInfo.IsMember));
}
{
Uri serviceUri = new Uri("[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUser[/url]");
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(serviceUri);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
//声明一个UserInfo类型的DataContractJsonSerializer实例
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserInfo));
//获取JSON数据流的信息,并将它转换成为UserInfo实例
UserInfo userInfo = (UserInfo)serializer.ReadObject(e.Result);//e.Result为JSON流数据
//下面显示userInfo中的数据信息
UserList.Items.Add(string.Format("Name:{0}, Address:{1}, Age:{2}, IsMember:{3} ",
userInfo.Name,
userInfo.Address,
userInfo.Age,
userInfo.IsMember));
}
因为DataContractJsonSerializer支持将JSON转换成本地的对象类型,所以我们可以像使用普通对象实例
一样。其运行结果如下图所示:
看明白了这段代码之后,再看另两个JSON类的使用方法就简单多了。其DEMO代码如下:
private void GetUserToJsonObject_Click(object sender, RoutedEventArgs e)
{
Uri serviceUri = new Uri("
http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUserListByAge/2");
WebClient webClient_JsonObject = new WebClient();
webClient_JsonObject.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClient_JsonObject_OpenReadCompleted);
webClient_JsonObject.OpenReadAsync(serviceUri);
}
void webClient_JsonObject_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
JsonObject jsonObject = (JsonObject) JsonObject.Load(e.Result);//e.Result为JSON流数据
//下面获取JSON对象实例中的数据
UserList.Items.Add(string.Format("Name:{0}, Address:{1}, Age:{2}, IsMember:{3} ",
jsonObject["Name"],
jsonObject["Address"],
jsonObject["Age"],
jsonObject["IsMember"]));
}
{
Uri serviceUri = new Uri("
http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUserListByAge/2");
WebClient webClient_JsonObject = new WebClient();
webClient_JsonObject.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClient_JsonObject_OpenReadCompleted);
webClient_JsonObject.OpenReadAsync(serviceUri);
}
void webClient_JsonObject_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
JsonObject jsonObject = (JsonObject) JsonObject.Load(e.Result);//e.Result为JSON流数据
//下面获取JSON对象实例中的数据
UserList.Items.Add(string.Format("Name:{0}, Address:{1}, Age:{2}, IsMember:{3} ",
jsonObject["Name"],
jsonObject["Address"],
jsonObject["Age"],
jsonObject["IsMember"]));
}
其运行结果如下所示:
最后再看一下JsonArray, 这个类可以看成是JsonObject的一个集合,它支持LINQ查询,其DEMO代码如下:
private void GetUserToJsonArray_Click(object sender, RoutedEventArgs e)
{
Uri serviceUri = new Uri("[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUserList[/url]");
WebClient webClient_JsonArray = new WebClient();
webClient_JsonArray.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClient_JsonArray_OpenReadCompleted);
webClient_JsonArray.OpenReadAsync(serviceUri);
}
void webClient_JsonArray_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
JsonArray users = (JsonArray)JsonArray.Load(e.Result);//e.Result为JSON流数据
var userlist = from user in users
where user["Age"] > 2
select user;
foreach (JsonObject jsonObject in userlist)
{
UserList.Items.Add(string.Format("Name:{0}, Address:{1}, Age:{2}, IsMember:{3} ",
jsonObject["Name"],
jsonObject["Address"],
jsonObject["Age"],
jsonObject["IsMember"]));
}
}
{
Uri serviceUri = new Uri("[url]http://localhost:1514/Json_SilverlightWeb/UserService.svc/GetUserList[/url]");
WebClient webClient_JsonArray = new WebClient();
webClient_JsonArray.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClient_JsonArray_OpenReadCompleted);
webClient_JsonArray.OpenReadAsync(serviceUri);
}
void webClient_JsonArray_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
JsonArray users = (JsonArray)JsonArray.Load(e.Result);//e.Result为JSON流数据
var userlist = from user in users
where user["Age"] > 2
select user;
foreach (JsonObject jsonObject in userlist)
{
UserList.Items.Add(string.Format("Name:{0}, Address:{1}, Age:{2}, IsMember:{3} ",
jsonObject["Name"],
jsonObject["Address"],
jsonObject["Age"],
jsonObject["IsMember"]));
}
}
运行结果如下图所示:
当然在JSON名空间下还有许多不错的类,如果大家有兴趣,我会在以后进行介绍:)
好了,今天的内容就先到这里了。
本文转自 daizhenjun 51CTO博客,原文链接:http://blog.51cto.com/daizhj/83870,如需转载请自行联系原作者