C#中使用JSON不需要使用第三方库,使用.NET Framwork3.5自带的System.Runtime.Serialization.Json即可很好的完成JSON的解析。
关于JSON的入门介绍见(首页的图很形象):
一、Using
需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
using
System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Runtime.Serialization;
二、定义序列化的类
假如我们要转化的JSON字符串格式为:
{
" encoding " : " UTF-8 " ,
" plug-ins " :[ " python " , " c++ " , " ruby " ],
" indent " :{
" length " : 3 ,
" use_space " : true
}
}
" encoding " : " UTF-8 " ,
" plug-ins " :[ " python " , " c++ " , " ruby " ],
" indent " :{
" length " : 3 ,
" use_space " : true
}
}
然后编写相应的序列化的类,注意下面类加的Attribute:

三、对象转化为JSON字符串
使用WriteObject方法:

四、JSON字符串转对象
使用ReadObject方法:

五、输出结果:
JSON
string
is
:
{ " encoding " : " UTF-8 " , " plugins " :[ " python " , " C++ " , " C# " ], " indent " :{ " length " : 4 , " use_space " : false }}
Encoding is : UTF - 8
plugins is : python
plugins is : C ++
plugins is : C#
indent.length is : 4
indent.use_space is : False
{ " encoding " : " UTF-8 " , " plugins " :[ " python " , " C++ " , " C# " ], " indent " :{ " length " : 4 , " use_space " : false }}
Encoding is : UTF - 8
plugins is : python
plugins is : C ++
plugins is : C#
indent.length is : 4
indent.use_space is : False
本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/11/25/1340862.html,如需转载请自行联系原作者