首页 > 技术文章 > Newtonsoft.Json 基本用法

jingping 2014-08-21 15:19 原文

Newtonsoft.Json 是.net 开源的一个json格式处理类库

官方网站:http://json.codeplex.com/

在使用的项目引用Newtonsoft.Json库。平常使用的方法有序列化与反序列方法

 

1 序列化:把一个对象序列化成json格式的字符串

       V_BBSTopic_User entity = db.GetTEntity<V_BBSTopic_User>(sql);
            if (entity != null)
            {
                string json = JsonConvert.SerializeObject(entity);  //序列化
                context.Response.Write(json);
            }

 Newtonsoft.Json 自定义时间格式

  如果不设置时间格式,它默认转为json 的时间格式是这样的:2014-08-29T12:23:234

默认格式明显不是我们想要的,所以必须使用IsoDateTimeConverter类设置时间格式

 IsoDateTimeConverter timeConverter=new IsoDateTimeConverter();
 timeConverter.DateTimeFormat="yyyy-MM-dd HH";
 string strJson = JsonConvert.SerializeObject(entity , Formatting.Indented, timeConverter);

 

 

2 反序列化:主要是把josn格式的字符串转化成一个实体对象。例如

public class A
    {
        public string ID { get; set; }
        public DateTime CreateDate { get; set; }
    }
//反序列化
string json="{'ID':'1','CreateDate ':'2014-08-20'}";
 A a = JsonConvert.DeserializeObject< A>(json);

 

3 Newtonsoft.Json 其它方法

//json 不能是数组
string jsonText2 = "{'a':'aaa','b':'bbb','c':'ccc'}";
JObject jobj = JObject.Parse(jsonText2);
Console.WriteLine("a:"+jobj["a"]);
Console.Read();

 

推荐阅读