Newtonsoft.Json 基本用法


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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM