Json for the .NET Compact Framework

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。(以上引自http://www.json.org/对JSON的介绍)

在美国的TechED 2008大会上,Andy Wigley讲了一节关于.NET Compact Framework访问RESTful Web Data Service的session,里面就提到了用JSON来序列化数据。以下是session的介绍:

Accessing RESTful Web Data Services in the Microsoft .NET Compact Framework: The Lightweight Alternative to SOAP
Most Microsoft developers are used to working with SOAP-based Web services and these RPC-like services have been used successfully in many mobile applications that need to access services hosted on remote servers. However, now there's a new kid on the block for remote data access that - its proponents claim - is lightweight, flexible, and works in the way the architects of the Web intended, using many of the built-in features of HTTP. REST stands for Representational State Transfer and is gathering supporters throughout the Web for its flexibility and the ease with which you can perform CRUD (Create, Read, Update, Delete) operations on remote data. Indeed, REST is used for exposing data in new Microsoft products such as ADO.NET Data Services and SQL Server Data Services. In this session, we compare the strengths and weaknesses of REST and SOAP, take a look at how to serialize data using JSON, and work through some demos to show how to program .NET Compact Framework applications that use REST to access services built with ADO.NET Data Services and those exposed by Web 2.0 APIs such as Facebook.

关于JSON数据格式的序列化,.NET Framework已经有了Json.NET (http://www.codeplex.com/Json),.NET Compact Framework也有了JsonCF (http://www.codeplex.com/JsonCF)。从JsonCF的作者Karl Seguin了解到,目前JsonCF还处于早期的版本,并没有经过充分的测试,所以用的时候需要注意一下。

示例代码:

string json = CodeBetter.Json.Converter.Serialize(new User("name""password", AccountStatus.Enabled));
CodeBetter.Json.Converter.Serialize(
"out.txt"new int[] { 123-4 }, "_");

User user 
= CodeBetter.Json.Converter.Deserialize<User>(json, "_");
int[] values = CodeBetter.Json.Converter.DeserializeFromFile<int[]>("out.txt""_");

 

由于JSON格式比SOAP简洁多了,在服务端和手机端之间传输用JSON序列化的数据,可以有效减少数据传输量,并提升传输速度。

posted @ 2008-12-24 01:11  黎波  阅读(4317)  评论(7编辑  收藏  举报