码迷,mamicode.com
首页 > Web开发 > 详细

Newtonsoft.Json 序列化和反序列化 时间格式

时间:2014-07-27 11:04:22      阅读:547      评论:0      收藏:0      [点我收藏+]

标签:

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

5.日期处理

public class LogEntry
{
  public string Details { get; set; }
  public DateTime LogDate { get; set; }
}

public void WriteJsonDates()
{
  LogEntry entry = new LogEntry
  {
    LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
    Details = "Application started."
  };

  // default as of Json.NET 4.5
  string isoJson = JsonConvert.SerializeObject(entry);
  // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

  JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
  {
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  };
  string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings);
  // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}

  string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
  // {"Details":"Application started.","LogDate":new Date(1234656000000)}
}

 

 

Newtonsoft.Json 序列化和反序列化 时间格式

标签:

原文地址:http://www.cnblogs.com/litian/p/3870975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!