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:

class Config
{
[DataMember(Order = 0 )]
public string encoding { get ; set ; }
[DataMember(Order = 1 )]
public string [] plugins { get ; set ; }
[DataMember(Order = 2 )]
public Indent indent { get ; set ; }
}
[DataContract(Namespace = " http://coderzh.cnblogs.com " )]
class Indent
{
[DataMember(Order = 0 )]
public int length { get ; set ; }
[DataMember(Order = 1 )]
public bool use_space { get ; set ; }
}
三、 对象转化为JSON字符串
使用WriteObject方法:

ITPUB个人空间!L8[,EqP&[
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/