作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明。如果你喜欢这篇文章,请点【推荐】。谢谢!

介绍

JSON是一个简单的,但功能强大的序列化数据格式。它定义了简单的类型,如布尔,数(int和float)和字符串,和几个数据结构:list和dictionnary。可以在http://JSON.org了解关于JSON的更多信息。

litjson是用C #编写的,它的目的是要小,快速,易用。它使用了Mono框架。

安装LitJSON

将LitJSON编译好的dll文件通过Import New Asset的方式导入到项目中,再使用Using LitJSON即可使用JSONMapper类中的简便方法。dll的下载地址在这里.

将JSON转化为Object并可逆向转化

为了在.Net程序中使用JSON格式的数据。一个自然的方法是使用JSON文本生成一个特定的类的一个新实例;为了匹配类的格式,一般存储的JSON字符串是一个字典。

另一方面,为了将对象序列化为JSON字符串,一个简单的导出操作,听起来是个好主意。

为了这个目的,LitJSON包引入了JsonMapper类,它提供了两个用于做到  JSON转化为object 和 object转化为JSON 的主要方法。这两个方法是jsonmapper.toobject和jsonmapper.tojson。

将object转化为字符串之后,我们就可以将这个字符串很方便地在文件中读取和写入了。

一个简单的JsonMapper的例子

在下面的例子中,ToObject方法有一个泛型参数,来指定返回的某种特定的数据类型:即JsonMapper.ToObject<T>。

using LitJson;
using System; public class Person
{
// C# 3.0 auto-implemented properties
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
} public class JsonSample
{
public static void Main()
{
PersonToJson();
JsonToPerson();
} public static void PersonToJson()
{
Person bill = new Person(); bill.Name = "William Shakespeare";
bill.Age = ;
bill.Birthday = new DateTime(, , ); string json_bill = JsonMapper.ToJson(bill); Console.WriteLine(json_bill);
} public static void JsonToPerson()
{
string json = @"
{
""Name"" : ""Thomas More"",
""Age"" : 57,
""Birthday"" : ""02/07/1478 00:00:00""
}"; Person thomas = JsonMapper.ToObject<Person>(json); Console.WriteLine("Thomas' age: {0}", thomas.Age);
}
}

上文的输出:

{"Name":"William Shakespeare","Age":,"Birthday":"04/26/1564 00:00:00"}
Thomas' age: 57

使用非泛型的JsonMapper.ToObject

当不存在特定的JSON数据类时,它将返回一个JSONData实例。JSONData是一种通用型可以保存任何数据类型支持JSON,包括list和dictionary。

using LitJson;
using System; public class JsonSample
{
public static void Main()
{
string json = @"
{
""album"" : {
""name"" : ""The Dark Side of the Moon"",
""artist"" : ""Pink Floyd"",
""year"" : 1973,
""tracks"" : [
""Speak To Me"",
""Breathe"",
""On The Run""
]
}
}
"; LoadAlbumData(json);
} public static void LoadAlbumData(string json_text)
{
Console.WriteLine("Reading data from the following JSON string: {0}",
json_text); JsonData data = JsonMapper.ToObject(json_text); // Dictionaries are accessed like a hash-table
Console.WriteLine("Album's name: {0}", data["album"]["name"]); // Scalar elements stored in a JsonData instance can be cast to
// their natural types
string artist = (string) data["album"]["artist"];
int year = (int) data["album"]["year"]; Console.WriteLine("Recorded by {0} in {1}", artist, year); // Arrays are accessed like regular lists as well
Console.WriteLine("First track: {0}", data["album"]["tracks"][]);
}
}

上面例子的输出:

Reading data from the following JSON string:
{
"album" : {
"name" : "The Dark Side of the Moon",
"artist" : "Pink Floyd",
"year" : ,
"tracks" : [
"Speak To Me",
"Breathe",
"On The Run"
]
}
} Album's name: The Dark Side of the Moon
Recorded by Pink Floyd in
First track: Speak To Me

Reader和Writer

一些人喜欢使用stream的方式处理JSON数据,对于他们, 我们提供的接口是jsonreader和jsonwriter。

JSONMapper实际上是建立在以上两个类的基础上的,所以你可以把这两个类当成是litJSON的底层接口。

使用JsonReader

using LitJson;
using System; public class DataReader
{
public static void Main()
{
string sample = @"{
""name"" : ""Bill"",
""age"" : 32,
""awake"" : true,
""n"" : 1994.0226,
""note"" : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ]
}"; PrintJson(sample);
} public static void PrintJson(string json)
{
JsonReader reader = new JsonReader(json); Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type");
Console.WriteLine (new String ('-', )); // The Read() method returns false when there's nothing else to read
while (reader.Read()) {
string type = reader.Value != null ?
reader.Value.GetType().ToString() : ""; Console.WriteLine("{0,14} {1,10} {2,16}",
reader.Token, reader.Value, type);
}
}
}

输出如下:

Token      Value             Type
------------------------------------------
ObjectStart
PropertyName name System.String
String Bill System.String
PropertyName age System.String
Int System.Int32
PropertyName awake System.String
Boolean True System.Boolean
PropertyName n System.String
Double 1994.0226 System.Double
PropertyName note System.String
ArrayStart
String life System.String
String is System.String
String but System.String
String a System.String
String dream System.String
ArrayEnd
ObjectEnd

最新文章

  1. STL的使用
  2. MongoDB 初见指南
  3. HTML5 CSS3学习
  4. Android点击效果
  5. 可拖拽的ListBox
  6. pthread_cond_timedwait时间设置
  7. C#中判断空字符串的3种方法性能分析
  8. Ext.Net_1.X_WINDOW遮罩层被GridPanel挡住
  9. 《Thinking in Android 9.0 系统开发源码钻研录》
  10. Python面试题练习
  11. git和github新手快速操作流程
  12. AdPlus
  13. Beta阶段敏捷冲刺四
  14. WPF经典编程模式-MVVM示例讲解
  15. Sangfor_AC用户不在线但在“在线用户管理”里有显示
  16. Android学习笔记九:Service
  17. iOS钱包卡券开发(往钱包里面加自己的卡券)
  18. Xshell和SecureCRT等SSH下使用Tmux及Byobu(解决Byobu被statusline信息面板刷屏问题)
  19. mysql分组取前N记录
  20. centos7.4 上面 docker 启动 cAdvisor 报错问题解决

热门文章

  1. passivedns 安装指南
  2. UIkit框架之UIimage
  3. FR #3题解
  4. HDOJ-三部曲一(搜索、数学)-1008-Prime Path
  5. C++ algorithm 里的sort函数应用
  6. JQuery源码解析(九)
  7. iOS 调用地图导航
  8. IOS 作业项目(4)步步完成 画图 程序(上)
  9. asp.net ToString()格式汇总
  10. 解决input之间的空隙