Newtonsoft.Json 序列化和反序列化 時間格式【轉】


1.JSON序列化

string JsonStr= JsonConvert.SerializeObject(Entity);

eg:

復制代碼
 
A a=new A();

a.Name="Elain00";

a.Hobby="eat eat";

string jsonStr=JsonConvert.SerializeObject(a);
 
復制代碼

 

2.JSON反序列化

string jsonstr = "jsonString";
Class model = JsonConvert.DeserializeObject<Class>(jsonstr);

eg:

string JsonStr='"{\'Name\':\'Elaine00\',\'Hobby\':\'eat eat\'}";
A a=JsonConvert.DeserializeObject<A>(JsonStr);

 3.時間格式處理

 IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                    timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                    Response.Write(JsonConvert.SerializeObject(bll.GetModelList(strWhere), Newtonsoft.Json.Formatting.Indented, timeFormat));

 

 4.擴展方法

復制代碼
public static class NewtonJSONHelper
    {
        public static string SerializeObject(this object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings{
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
        }

        public static T DeserializeObject<T>(this string data)
        {
            return JsonConvert.DeserializeObject<T>(data, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        }
    }
復制代碼


免責聲明!

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



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