一,基础知识
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。相对于xml,JSON与JavaScript的交互更加方便、体积更小、速度更快,天生利于网络传输。
JSON建构有两种结构:
1. “名称/值”对的集合(A collection of name/value pairs)。数据结构为 {key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,如:
{ "Name": "Tom", "Age":"23", "Gender": "Male" }
2. 数组,它是值的有序列表。一个数组以“[”开始,“]”结束。值之间使用“,”分隔。如:
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
这样就可以组成比较复杂的json数据:
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }
关于json的格式,可以用在线工具测试格式是否正确:http://www.bejson.com/go.php?u=http://www.bejson.com/index.php
本文通过在项目中引入第三方Newtonsoft.Json.dll解析json数据,下载地址:http://json.codeplex.com/
void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { try { var serializer = new Newtonsoft.Json.JsonSerializer(); var reader = new JsonTextReader(new StringReader(e.Result)); var info = serializer.Deserialize<OraLoginInfo>(reader); var emsInfo = new LoginInfo(info); this.LoginCompleted(this, new LoginCompletedEventArgs { Result = emsInfo }); } catch (Exception exp) { Log(exp.Message); this.LoginCompleted(this, new LoginCompletedEventArgs { Result = null, Error = exp }); } }